JS学习笔记——原生Ajax总结
1、创建兼容ie7+的xhr对象
var xhr=new XMLhttpRequest();
2、完整的发送ajax请求
var xhr=new XMLhttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readystate==4){
if(xhr.status>=200&&xhr.status<=300||xhr.status==304){
alert(xhr.responseText);
}else{
alert("Request Failed:"+xhr.status);
}
}
}
xhr.open("get","1.txt","true"); //启动请求以备发送
xhr.send(); //发送请求
3、xhr相关属性
- responseText:返回的文本
- responseXML:XML DOM,若非XML数据,值为null
- readystate:ajax阶段
- 0:未初始化
- 1:已经启动
- 2:已经发送
- 3:开始接收
- 4:接收完成
- status:http状态
- statusText:http状态说明
4、GET
//给URL末尾添加参数
function addURLParam(url,name,value){
url+=(url.indexOf('?')==-1?"?":"&");
url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
return url;
}
//创建请求URL
var url="example.php"
url=addURLParam(url,"name","Nico");
url=addURLParam(url,"book","Love Math");
5、POST
xhr.open("post", "postexample.php", true);
//修改Content-Type头部信息
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var form = document.getElementById("user-info");
xhr.send(serialize(form));