![0507b3924e165d6fb960fe74ae79f2d4.png](https://img-blog.csdnimg.cn/img_convert/0507b3924e165d6fb960fe74ae79f2d4.png)
为了一步步地理清封装步骤,我打算逐步封装ajax函数的功能,分成了以下6个版本:
Version 1
function ajax (method, url, params) {
xhr.open(method, url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') //针对post的设置请求头
params = params || null
xhr.send(params)
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return
console.log(this.responseText)
}
}
ajax('GET','xxx.php','id=1');
ajax('POST','xxx.php','key1=value1&key2=value2');
说明:
- 未兼容低版本 IE
- 这种方法在传参数的时候只能上例所示的格式,无法用json格式;
- 当method为get的时候,参数没正确地加在url后面无法起到作用;
- method为get时也是设置了('Content-Type', 'application/x-www-form-urlencoded')的请求头,但是这是不必要的。
- 把函数的结果写死了,总是console.log(this.responseText)
Version 2
function ajax (method, url, params) {
method = method.toUpperCase() //统一为大写,避免实参为小写的情况造成下面匹配时出错
//解决XMLHttpRequest在ie6不兼容的问题
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
if (method === 'GET') {
url += '?' + params
}
xhr.open(method, url)
var data = null
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
data = params
}
xhr.send(data)
xhr.onreadystatechange = function () {
if (this.readyState !==