平时我们在做项目时通常利用jQuery封装好的ajax函数:$.ajax(),
$.get(),$.post(),用起来很方便,但是很多小伙伴都不知道ajax底层实现原理,了解原理有助于我们更好的开发,拓展
#######Ajax:异步的ajax和xml
建立XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
2.设置回调函数
XmlHttp.onreadyStatechange = callback;
callback=function(){}
3.与服务器建立连接并向服务器发送请求
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
图片来自w3school手册
get请求写法:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
post请求需加请求头
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
图片来自w3school手册
4.服务器响应,在回调函数中对不同状态作出处理
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
如需获得来自服务器的响应,用 XMLHttpRequest 对象的 responseText 或 responseXML 属性
Paste_Image.png
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
图片来自w3chool手册