使用 XMLHttpRequest 实现 ajax

使用 XMLHttpRequest 实现 ajax

function ajax (url, method, body, headers) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()
    request.open(method, url) // 初始化一个请求
    for (let key in headers) {
      request.setRequestHeader(key, headers[key]) // 设置HTTP请求头部的方法,该方法必须在 open()之后,send() 之前调用
    }
    request.onreadystatechange = () => {
      // debugger
      if (request.readyState === 4) {
        if (request.status === 200 || request.status === 304) {
          resolve(request.responseText) // request.responseText 是一个字符串,需要 JSON.parse() 转换
        } else {
          reject(request)
        }
      }
    }

    request.send(body) // 发送http请求
  })
}

ajax('./data.json', 'get').then(res => {
  console.log(res)
})

XMLHttpRequest解析

XMLHttpRequest(xhr)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定URL,获取数据。运行网页在不影响用户操作的情况下,更新页面的局部内容

构造函数

XMLHttpRequest()

该构造函数用于初始化一个 XMLHttpRequest 实例对象。在调用任何其他方法之前,必须先调用该构造函数,得到一个实例对象。

常用方法

XMLHttpRequest.open()

方法初始化一个请求,在js代码中使用

xhrReq.open(method, url)
// xhrReq.open(method, url, async, user, password) // async: boolean,默认true,是否执行异步操作

XMLHttpRequest.send()

方法用于发送HTTP请求,接收一个可选的参数,作为请求主体,如果请求方法是 GET 或 HEAD,则应将请求主体设置为 null

XMLHttpRequest.send(body)

XMLHttpRequest.setRequestHeader()

方法是设置HTTP请求头部的方法,该方法必须在 open() 方法之后,send() 方法之前调用

xhrReq.setRequestHeader(header, value) // header 属性的键,value 属性的值

常用属性

readyState

XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest 代理当前所处的状态,一个XHR代理总是处于下面状态中的一个

0  代理被创建,但尚未调用open()方法
1  open() 方法已经被调用
2  send() 方法已经被调用,并且头部和状态已经可获得
3  下载中,responseText 属性已经包含部分数据
4  下载操作已完成

responseText

XMLHttpRequest.responseText 在一个请求被发送后,从服务器端返回文本

const resultText = XMLHttpRequest.responseText // 返回纯文本的值

当请求状态 readyState 变为4,且status值为200时,responseText是全部后端的返回数据。

status

只读属性 XMLHttpRequest.status 返回了 XMLHttpRequest 响应中的数字状态码。

如 status 200代表一个成功的请求。

timeout

XMLHttpRequest.timeout代表一个请求在被自动终止前所消耗的毫秒数。默认值为0,意味着没有超时。

const xhr = new XMLHttpRequest()
xhr.open('GET', '/server')

xhr.timeout = 2000 // 单位毫秒,超时时间

xhr.onload = function () {
    // 请求完成 ,在此进行处理
}
xhr.ontimeout = function (error) {
    // XMLHttpRequest 超时,在此进行处理
}

xhr.send(null)

withCredentials

XMLHttpRequest.withCredentials 属性是一个 Boolean 类型,指示了是否该使用类似cookies, authorization headers来创建一个跨站点访问控制请求。在同一个站点下使用 withCredentials 属性是无效的。

如果在发送来自其他域的XMLHttpRequest 请求之前,设置 withCredentials 为true,可以获得第三方cookies。

const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://example.com', true)
xhr.withCredentials = true
xhr.send(body)

常用事件

onreadystateChange

只要 readyState 属性发生变化,就会调用相应的处理函数。

XMLHttpRequest.onreadystateChange = callback
const xhr = new XMLHttpRequest(),
      method = 'GET',
      url = 'http://example.com'
xhr.open(method, url, true)
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
    }
}
xhr.send()
// load()
request.onload = (error) => {
    console.log('DONE', xhr.status)
}
// error()
request.onerror = (error) => {
    console.log(error)
}
// timeout()
request.ontimeout = (error) => {
    console.log(error)
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值