Ajax技术核心是 XMLHttpRequest,工做原理能够分为4步html
一、建立Ajax对象浏览器
var xhr = new XMLHttpRequest();
二、链接服务器服务器
xhr.open('get','test.html',true);
三、发送请求spa
xhr.send();
四、获取响应code
xhr.onreadystatechange = function(){
if(xhr.readystate == 4){ //请求的状态码
/*
0:请求尚未创建(open执行前)
1:请求创建了还没发送(执行了open)
2:请求正式发送(执行了send)
3:请求已受理,有部分数据能够用,但尚未处理完成
4:请求彻底处理完成
*/
alert(xhr.responseText); //返回的数据
}
}
下面是完整代码htm
function loadXMLDoc(){ var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); //非IE浏览器建立 XMLHttpRequest 对象 }else { xhr = new ActiveObject("Microsoft.XMLHTTP"); //IE浏览器建立 XMLHttpQuest 对象 } xhr.open('get','test.html',true); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ document.getElementById("myDiv").innerHTML = xhr.reponseText; } }}