原生js发送Ajax请求

一、通过onload注册事件

// 1. 创建一个 xhr 对象
var xhr = new XMLHttpRequest();
// 2. 设置请求的方式和路径
xhr.open('GET', '/time');
// 3. 发送请求
xhr.send(null);
// 4. 注册事件
xhr.onload = function () {
    // 通过 xhr 的 responseText 获取到响应的响应体
   console.log(this.responseText)
}

  注意:如果是发送post方式的请求,需要在open和send中间设置请求头,send中添加要传递的参数(有格式要求:=连接属性和值;&连接不同的属性)。

var xhr = new XMLHttpRequest()
xhr.open('POST', '/query-post')
// 设置 Content-Type 为 application/x-www-form-urlencoded,这行代码不用死记硬背,去复制即可
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 需要提交到服务端的数据可以通过 send 方法的参数传递
// 格式:name=zhangsan&age=18
xhr.send('name=zhangsan&age=18')
xhr.onload = function () {
    console.log(this.responseText)
}

二、通过onreadystatechange注册事件

  onload 是 HTML5 以后新增的方便获取响应的事件,过去获取浏览器返回内容的时候使用的是 onreadystatechange。

var xhr = new XMLHttpRequest()
// open 方法的第一个参数的作用就是设置请求的 method
xhr.open('POST', '/query-post')
// 设置 Content-Type 为 application/x-www-form-urlencoded,这行代码不用死记硬背,去复制即可
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 需要提交到服务端的数据可以通过 send 方法的参数传递
// 格式:name=zhangsan&age=18
xhr.send('name=zhangsan&age=18')
// 更改事件为onreadystatechange
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
    // 后续逻辑......
  }
} 

 

原文地址:https://www.cnblogs.com/belongs-to-qinghua/p/11353114.html