1. 建立 xmlHttpRequest 对象
- if(window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- if(xmlHttp.overrideMimeType) {
- xmlHttp.overrideMimeType("text/xml");
- }
- } else if(window.ActiveXobject) {
- var activeName = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
- for(var i = 0; i < activeName.length; i++) {
- try {
- xmlHttp = new ActiveXobject(activeName[i]);
- break;
- } catch(e) {}
- }
- }
- if(!xmlHttp) {
- alert("创建 xmlhttprequest 对象失败");
- } else {}
2. 设置回调函数
- xmlHttp.onreadystatechange= callback;
- function callback(){}
3. 使用 OPEN 方法与服务器建立连接 xmlHttp.open("get","ajax?name="+ name,true)
此步注意设置 http 的请求方式 (post/get), 如果是 POST 方式, 注意设置请求头信息 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
4. 向服务器端发送数据
xmlHttp.send(null);
如果是 POST 方式就不为空
5. 在回调函数中针对不同的响应状态进行处理
- if(xmlHttp.readyState == 4){ // 判断交互是否成功
- if(xmlHttp.status == 200){ // 获取服务器返回的数据 // 获取纯文本数据
- var responseText =xmlHttp.responseText;
- document.getElementById("info").innerhtml = responseText;
- }
- }
来源: http://www.bubuko.com/infodetail-2611501.html