当前位置: 移动技术网 > IT编程>脚本编程>Ajax > js基本ajax写法示例代码

js基本ajax写法示例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

var xmlhttp = null;
function myajax() {
//1、创建xmlhttprequest对象
//2、需要针对ie和其它浏览器建立这个对象的不同方式写不同的代码
if (window.xmlhttprequest) {
//针对ff,mozilar,opera,safari,ie7,ie8
xmlhttp = new xmlhttprequest();
//修正某些浏览器bug
if (xmlhttp.overridemimetype) {
xmlhttp.overridemimetype("text/xml");
}
} else if (window.activexobject) {
//针对ie6以下的浏览器
var activexname = ["msxml2.xmlhttp", "microsoft.xmlhttp", ""];
for (var i = 0; i < activexname.length; i++) {
try {
//取出一个控件名称创建,如果创建成功则停止,反之抛出异常
xmlhttp = new activexobject(activexname[i]);
break;
} catch (e) { }
}
}

//需要确认xmlhttp创建是否成功
if (!xmlhttp) {
alert("xmlhttprequest创建失败!");
return;
} else {
alert(xmlhttp);
}

//注册回调函数。注意注册回调函数是不能加括号,加了会把函数的值返回给onreadystatechange
xmlhttp.onreadystatechange = callback;
//设置连接信息
//第一个参数表示http请求方式,支持所有http的请求方式,主要使用get和post
//第二个参数表示请求的url地址,get方式请求的参数也在urlkh
//第三介参数表示采用异步还是同步方式交互,true表示异步
xmlhttp.open("get", "servlet/checkusername?username=" + username, true);
//发送数据表示和服务器端交互
//同步方式下,send这名话会在服务器端数据回来后才执行完
xmlhttp.send(null);

//异步方式下,send这句话立即完成执行
//post方式请求的代码
//xmlhttp.open("post","servlet/checkusername",true);
//post方式需要自己设置http的请求头
//xmlhttp.setrequestheader("content-type","application/x-www-form-urlencoded");
//post方式发送数据
//xmlhttp.send("username="+username);
}

//回调函数
function callback() {
//判断对象的状态是交互完成
if (xmlhttp.readystate == 4) {
//判断http的交互是否成功
if (xmlhttp.status == 200) {
//获取服务器端返回的数据
//获取服务器端输出的纯文本数据
var responsetext = xmlhttp.responsetext;
alert(responsetext);
}
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网