使用xhr发起POST请求

  • 创建 xhr 对象

  • 调用 xhr.open() 函数

  • 设置 Content-Type 属性(固定写法)

  • 调用 xhr.send() 函数,同时指定要发送的数据

  • 监听 xhr.onreadystatechange 事件

// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
// 3. 设置 Content-Type 属性(固定写法)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
// 5. 监听事件
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText)
  }
}

 

posted @ 2023-02-01 15:18  Harry宗  阅读(1101)  评论(0编辑  收藏  举报