js封装ajax请求

1.了解prototype

原型对象的作用,就是定义所有实例对象共享的属性和方法。具体理解见实际操作中

2.给String Date等对象增加继承方法

要求结果:比如var date = “2016-01-01 00:00:00”;date.format();要求输出”2016-01-01”;

1
2
3
4
5
String.prototype.format = function(){
return this.substring(0,10);
};
var str1 = "2016-01-01 00:00:00";
alert(str1.format(str1));

3.了解xmlhttprequest,能发送及接受ajax,以及分析response对象

response属性为只读,返回接收到的数据体(即body部分),他的类型可以是ArrayBuffer、Blob、Document、JSON对象、或者一个字符串。由XMLHttpRequest.responseType属性的值决定。

4.结合xmlhttprequest+prototype 自己封装一个请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
XMLHttpRequest.prototype.ajax = function(type,url,data,success,error){
var _this = this;
if(typeof data == 'object'){
var tempStr = '';
for(var key in data){
tempStr += key + '=' + data[key] + '&';
}
data = tempStr.replace(/&$/,'');
}
if(type = 'GET'){
if(data){
this.open('GET',url + '?' + data, true);
}else{
this.open('GET',url + '?version=' + Math.random(),true);
}
this.send();
}else if(type == 'POST'){
this.open('POST',url,true);
this.setRequestHeader("content-type","application/x-www-form-urlencoded");
this.send(data);
}
this.onreadystatechange = function () {
if(this.readyState == 4){
if(this.status == 200){
success(this.responseText);
}else{
if(error){
error(this.status);
}
}
}
}
};

//ajax test
var xhr = new XMLHttpRequest();
xhr.ajax('GET','/test.json',null,function(data){
alert(data);
});