1、创建 XMLHttpRequest 对象
为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :
//
var xmlhttp = null ;
function createXmlhttp() {
if(window.XmlhttpRequest) {
xmlhttp = new XmlHttpRequest();
}
if(window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("microsoft.XMLHTTP") ;
}catch(e) {
xmlhttp = new ActiveXObject("msxml2.XMLHTTP");
}
}
if(!xmlhttp) {
alert("创建xmlhttp对象异常!");
return false;
}
}
2、向服务器发送请求
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("POST","ajax_test.action",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //向请求添加 HTTP 头
xmlhttp.send("fname=Bill&lname=Gates"); //请求的数据
3、服务器两种响应方式
responseText获得字符串形式的响应数据。
responseXML获得 XML 形式的响应数据。
4、onreadystatechange 事件
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
详细请参考