XHR

  1. 概述
    XMLHttpRequest (xhr)是浏览器提供的Javascript对象,通过它,可以请求服务器上的数据资源。jQuery中的Ajax函数,就是基于xhr对象封装出来的。

  2. 使用xhr发起get请求

//1.创建XHR对象
var xhr = new XMLHttpRequest ()
// 2.调用open函数,指定请求方式与URL地址
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
// 3.调用send函数,发起Ajax请求
xhr.send ()
// 4.监听onreadystatechange 事件
xhr.onreadystatechange = function() {
// 4.1监听xhr对象的请求状态readystate ;与服务器响应的状态status
if (xhr.readystate === 4 & xhr.status === 200) {
// 4.2 打印服务器响应回来的数据
console.log (xhr.responseText)
}
  1. readystate属性,用来表示当前Ajax请求所处的状态。

    4.使用xhr发起带参数的GET请求
    只需在调用xhr.open期间,为URL地址指定参数即可,这种在URL地址后面拼接的参数,叫做查询字符串(指在URL的末尾加上用于向服务器发送信息的字符串<变量>)。
  2. URL编码
encodeURL()//编码,,,中->英
decodeURL()//解码,,,英->中
  1. 使用xhr发起POST请求
//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=施耐庵spublisher=天津图书出版社')
// 5.监听onreadystatechange 事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log (xhr.responseText)
posted @ 2022-06-11 13:31  MuJinHK  阅读(639)  评论(0)    收藏  举报