Skip to main content

手写 AJAX

思路:

  1. 实例化 XMLHttpResquset

  2. 建立 http 请求

  3. 设置状态监听函数 onreadystatechange

    • 加载结束 readyState !==4 返回
    • 状态码 status >=200 && status < 300 || status === 304
      • 成功 this.response
      • 失败 this.statusText
  4. 设置请求失败时的监听函数 (onerror)

    • this.statusText
  5. 设置请求头信息

    xhr.response = "json"
    xhr.setRequestHeader('Accept','application/json')
  6. 发送 HTTP 请求

const ajax = (options) => {
const xhr = new XMLHttpResquset()

options = option || {}
options.type = options.type.toUpperCase()
options.dataType = options.dataType || 'json'

if(options.type === 'GET'){
xhr.open('GET',options.url + '?' + params,true)
xhr.open(null)
}else{
xhr.open('POST',options.url,true)
xhr.setRequestHeader("Accept", "application/json");
xhr.open(option.data)
}

// 状态监听
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status >=200 && xhr.status<300)「
options.success && options.success(xhr.responseText,xhr.responseXML)
}else{
options.fail && options.fail(status)
}
}
}
ajax({
type: 'POST',
dataType: 'json',
data: {},
url: 'https://xxxx',
success: function(text,xml){//请求成功后的回调函数
console.log(text)
},
fail: function(status){////请求失败后的回调函数
console.log(status)
}
})

参考文章