写在前面:响应事件
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + type, function () {
fn.call(obj);
});
}
}
核心
Ajax技术核心是XMLHttpRequest对象,简称XHR.如果是IE6及以下需要使用ActiveX对象通过MSXML库实现。
当请求发送到服务器端,收到响应后,响应的数据会自动填充XHR对象的属性,总共有四个属性:
在接受响应之后,第一步检查status属性,以确定响应已经成功返回。HTTP状态代码为200作为成功标志。除此之外还有其他的。
判断HTTP状态值即可,一般不使用HTTP状态说明,在跨浏览器的时候可能会不太一样。
1 function creatXHR() {
2 if (typeof XMLHttpRequest != 'undefined') {
3 return new XMLHttpRequest();
4 } else if (typeof ActiveXObject != 'undefined') {
5 var version = [
6 'MSXML2.XMLHttp.6.0',
7 'MSXML2.XMLHttp.3.0',
8 'MSXML2.XMLHttp'
9 ];
10 for (var i = 0; version.length; i ++) {
11 try {
12 return new ActiveXObject(version[i]);
13 } catch (e) {
14 //跳过
15 }
16 }
17 } else {
18 throw new Error('您的系统或浏览器不支持XHR对象!');
19 }
20 }
21 var xhr = new createXHR();
在使用XHR对象时,先必须调用open()方法,它接收三个参数,
要发送请求类型(get/post),请求的url和表示是否异步(false/true)。
1 addEvent(document,"click", function(){
2 var xhr = creatXHR();
3 xhr.open('get','demo.php?rand=' + Math.random(),false);
4 xhr.send(null);
5 if (xhr.status == 200) {
6 alert(xhr.responseText);
7 }else {
8 alert('获取数据错!错误代码:' + xhr.status + ',错误信息:' + 'xhr.statusText' );
9 }
10 });
上面是使用get方法同步调用,在使用异步调用的时候,需要触发readystatechange事件,然后检测readyState属性,改属性有五个值
使用abort()方法可以取消异步请求,放在send()方法之前会报错,放在responseText之前会得到一个空值。
addEvent(document,'click',function () {
var xhr = creatXHR();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText);
}else{
alert('获取数据错误!错误代码:' + xhr.status + ',错误信息:'+ xhr.statusText);
}
}
};
xhr.open('get','demo.php?rand=' + Math.random(), true);
//xhr.abort();
xhr.send(null);
})
GET和POST
在服务器请求的过程中,有两种方式,分别是get和post。在Ajax中使用get方式要高于post。
http头部信息,包含服务器返回的响应头信息和客户端发送出去的请求信息。
响应头信息:-->服务器返回信息,客户端可以获取,但不可以设置。
请求头信息:-->客户端发送的信息,客户端可以设置,但不可以获取。
使用getALLResponseHeader()获取整个响应头信息。
使用getResponseHeader()获取单个响应头信息。
使用setRequestHeader()设置单个请求头信息
PS:js中只可以获取服务器返回回来响应头信息,无法获取向服务器提交的请求头信息。
1 addEvent(document,'click',function () {
2 var xhr = creatXHR();
3 xhr.onreadystatechange = function () {
4 if (xhr.readyState == 4) {
5 if (xhr.status == 200) {
6 //alert(xhr.getAllResponseHeaders());
7 alert(xhr.getResponseHeader('Content-Type'))//--?text/html ;
8 }else{
9 alert('获取数据错误!错误代码:' + xhr.status + ',错误信息:' + xhr.status);
10 }
11 }
12 }
13 xhr.open('get','demo.php?rand=' +Math.random(), true);
14 xhr.setRequestHeader('myheader','cc'); -->放在open()之后,send()之前
15 xhr.send(null);
16 });
1.get请求
get常用于服务器查询某些信息,必要时,可以将查询字符串参数追加到URL的末尾,以便提交给服务器。‘
xhr.open('get','demo.php?rand=' +Math.random(), true);
通过URL后的问号给服务器传递键值对数据,服务器接收到返回响应数据,特殊字符传参产生的问题可以使用encodeURLComponent()j进行编码处理,中文字符的返回及传参,可以将页面保存和设置为utf-8格式即可。
2.post请求
在使用表单提交时候,很多使用post传输方式
xhr.open("post","demo.php",true);
发送POST请求的数据,不会跟在url后,而是通过send()方法向服务器提交数据。
xhr.send('name=CC&age=100');
一般来说,向服务器发送POST请求由于解析机制的原因,需要进行特别的处理。因为POST
请求和Web表单提交是不同的,需要使用XHR来模仿表单提交。
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
从性能上讲POST请求比GET请求消耗更多一些。
封装Ajax
ajax使用起来比较复杂,主要是因为涉及到是使用get还是post,是同步还是异步,所以需要封装一些,以方便以后使用:
1 function ajax(obj){ 2 var xhr = creatXHR(); 3 obj.url = obj.url+'?rand=' + Math.random(); 4 obj.data = params(obj.data); 5 if (obj.method === 'get') obj.url += obj.url.indexOf("?") == -1?'?' + obj.data:'&' + obj.data; 6 if (obj.async === true) { 7 xhr.onreadystatechange = function(){ //-->异步加载 8 if (xhr.readyState == 4) { 9 if (xhr.status == 200) { 10 alert(xhr.responseText); 11 }else{ 12 alert('获取数据错误!错误代码:' + xhr.status + ',错误信息:' + xhr.status); 13 } 14 } 15 if (xhr.readyState == 4) { 16 callback(); 17 } 18 } 19 } 20 xhr.open(obj.method,obj.url,obj.async); 21 if (obj.method === 'post') { 22 xhr.setRequestHeader('Content-Type','application/x-wwww-form-urlencoded'); 23 xhr.send(obj.data); 24 }else{ 25 xhr.send(null); 26 } 27 28 if (obj.async === false) { 29 callback() 30 } 31 32 function callback() { 33 if (xhr.status ==200) { 34 obj.success(xhr.responseText); 35 }else{ 36 alert('获取数据错误!错误代码:' + xhr.status+ ',错误信息:' + xhr.statusText); 37 } 38 } 39 40 } 41 //调用ajax 42 addEvent(document,'click',function () { 43 44 ajax({ 45 method:'post', 46 url:'demo.php', 47 data:'name=cc&age=50', 48 success:function (text) { 49 alert(text); 50 }, 51 async:false 52 }); 53 });
//名值对编码
function params(data) {
var arr = [];
for(var i in data){
arr.push(encodeURIComponent(i) + '=' +encodeURIComponent(data[i]));
}
return arr.join('&');
}