==ajax技术可以向服务器请求额外的数据而无需卸载页面==。其核心技术是XMLHttpRequest对象(XHR)。
IE7以前的旧版本经过MSXML库中的ActiveX对象实现。而IE7及以后的浏览器支持XMLHttpRequest构造函数
能够作兼容性的createXHR();php
function createXHR(){ //检查是否支持XMLHttpRequest if(typeof XMLHttpRequest!="undefined") { //支持,返回XMLHttpRequest对象 return new XMLHttpRequest(); } //若是不支持XMLHttpRequest,就检查是否支持ActiveXObject else if(typeof ActiveXObject !="undefined") { //检查activeXString if(typeof arguments.callee.activeXString!="string") { var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len; for(i=0,len=versions.length;i<len,i++) { try{ //看是否有能够支持的版本 new ActiveXObject(versions[i]); arguments.callee.activeXString=versions[i]; break; } catch(ex){ //跳过 } } } //返回ActiveXObject return new ActiveXObject(arguments.callee.activeXString); } else { //都不行 throw new Error("NO XHR object availablle"); } }
这个例子先检查XHR对象是否存在,存在就返回XHR对象,不存在就检查ActiveX对象是否存在,存在就返回,若是两个对象都不存在,就返回错误。ajax
XHR有一个方法叫open(),接收三个参数,请求方式(get,post),请求的url,表示是否异步请求的布尔值(true为异步)跨域
let xhr=createXHR(); xhr=open('get','https://www.baidu.com',flase);
==open()方法不会直接发送请求,而是启用一个请求以备发送==浏览器
XHR还有一个方法叫send(),接收一个参数,即做为请求主体要发送的数据。
==send()和open()配合使用就能够发送特定的请求==。服务器
xhr=open('get','https://www.baidu.com',flase); xhr.send(null);
上面代码是同步执行的,因此要等服务器响应请求后js代码才会继续执行。服务器响应后会自动为XHR对象填充如下信息:app
属性 | 描述 |
---|---|
responseText | 做为响应主题被返回的文本 |
responseXML | 若是响应的内容是"text/xml"或"application/xml",这个属性将保存响应数据的XML DOM文档 ,若是不是xml文件,这个值为空 |
status | HTTP的响应状态 |
statusText | HTTP响应状态说明 |
尽可能不要用statusText去判断,statusText在跨域时不太可靠。异步
if((xhr.status>=200&&xhr.status<=300)||xhr.status===304) { //success console.log("status success"); } else { console.log("status fail"); }
注意:浏览器有时候会错误的报告204状态,IE的XHR的ActiveX会将201设置为1223,IE中原生的XHR会将204规范为200,而opera或将status设置为0。函数
能够检测XHR对象的readyState属性来求得请求/响应的当前阶段post
这些阶段的改变会触发readystatechange事件,能够根据该事件来检测readyState编码
//onreadystatechange事件要在open以前指定,保证跨域浏览器的兼容性 xhr.onreadystatechange=function(){ if(xhr.readyState===4) { if((xhr.status>=200&&xhr.status<=300)||xhr.status===304) { //success console.log("status success"); } else { console.log("status fail"); } } } xhr.open("get","https://www.baidu.com",true); xhr.send(null);
能够用xhr.abort()在响应前取消异步请求,
这个方法会使XHR中止触发时间,不再容许访问与响应有关的对象属性,这个方法在请求终止后还会对XHR解引,不建议XHR重用,会影响内存。
xhr.open("get","www.baidu.com",true); // 不要使用浏览器正常字段,会影响浏览器响应 xhr.setRequestHeader("MyHeader","MyValue"); xhr.send(null);
var MyHeader=xhr.getResponseHeader('Content-Type'); var allHeader=xhr.getAllResponseHeader();
get请求经常使用于向服务器查询某些信息。
//这里的查询字符串须要正确的编码 xhr.open("get","example.php?name=name1&age=age1",true);
GET请求常常发生的错误是查询字符串的格式问题,查询字符串中的每一个参数名和值都须要encodeURIComponent()来先进行编码。
/** * [对查询字符串进行编码] * @param {[type]} url [要添加的参数的url] * @param {[type]} name [参数名] * @param {[type]} value [参数值] */ function addURLParam(url,name,value) { url+=(url.indexOf("?")===-1?"?":"&"); url+=encodeURIComponent(name)+"="+encodeURIComponent(value); return url; }
使用这个函数能够保证查询字符串的格式良好,能可靠的用于XHR对象
post请求用于向服务器发送应该被保存的数据,把数据做为请求主体提交。
post请求能够提交XML文档
xhr.open("post","example.php",true) xhr.send(data);
默认状况下,服务器对post请求和Web表单提交不会一视同仁。若是须要提交表单,可使用以下代码
/** * post提交表单 * @return {[type]} [description] */ function submitData(){ var xhr=createXHR(); xhr.onreadystatechange=function(){ if(xhr.readyState===4) { if((xhr.status>=200&&xhr.status<=300)||xhr.status===304) { //success console.log("status success"); } else { console.log("status fail"); } } } xhr.open("post","example.php",true); //设置头部信息为表单提交时的内容 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var form=document.getElementById("user-info"); //将表单数据序列化 xhr.send(serialize(form)); }