Ajax的核心是XMLHttpRequest对象,然后我们通过使用JavaScript向服务器提出请求并处理响应,而不阻塞用户。也就是说在我们发出Ajax请求的同时,服务器开始处理数据,用户可以去做别的事情,不需等待这个过程,直到服务器告诉用户处理完成即可。
第一步,初始化XMLHttpRequest对象:
function createXMLHttpRequest(){
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
return xmlHttp;
}
注册监听,服务器返回信息时,客户端的处理:
xmlHttp.onreadystatechange = function(){//由服务器触发该事件处理函数
if(xmlHttp.readyState ==4){ //处理服务器返回的信息
if(xmlHttp.status == 200){
document.getElementById("result").innerHTML = xmlHttp.responseText;//将传回的信息当字符串使用
}
}
};
建立对服务器的调用,发出get请求:
xmlHttp.open("get","http://localhost/xxx/xxx1/dataProcess",true);
向服务器发送数据:
xmlHttp.send(null);