1.建立XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
2.注册回调函数
xmlhttp.onreadystatechange=callback;
3.使用open方法设置和服务器交互的基本信息
GET请求
xmlhttp.open("GET","url",true);
xmlhttp.send();
POST请求
xmlhttp.open("Post","AJAX",true )
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=" + UserName);
4.设置发送的数据,开始和服务器端交互
xmlhttp.send(); //这里针对以上步骤中的send操作,但是set与post不同,这里没做区别
5.在回调函数中判断交互是否结束,相应是否正确并根据需要获取服务器端返回的数据,更新页面
function callback() { //交互是否完成,是否正确返回数据
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
var message =xmlhttp.responseText;
var div =document.getElementById("message");
div.innerHTML=message;
}
}
}