概念
XMLHttpRequest(简称
xhr)是浏览器提供的
Javascript` 对象,通过它,可以请求服务器上的数据资源。之
前所学的 jQuery
中的 Ajax 函数,就是基于 xhr
对象封装出来的
使用xhr发起GET请求
一共分为四步
第一步 用new关键字创建一个xhr对象
const xhr = new XMLHttpRequest()
第二步 调用xhr.open()函数 这个函数第一个参数相当于选定GET或者POST方法 第二个代表我们需要发起请求的地址
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
第三步 调用xhr.send()函数 使其运行
xhr.send()
第四步 监听 xhr.onreadystatechange事件
xhr.onreadystatechange = function() {
if (xhr.readyState == 4&&xhr.status == 200){
console.log(xhr.responseText);
}
}
我们看看运行结果如何
了解xhr对象的readyState属性
XMLHttpRequest
对象的 readyState
属性,用来表示当前 Ajax
请求所处的状态。
它有以下几种状态
使用xhr发起带参数的请求
只要在open中的url最后面加上?和你的参数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
如果是多个参数就用&符号隔开
如
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记')
无论使用 $.ajax()
,还是使用 $.get()
,又或者直接使用 xhr
对象发起 GET
请求,当需要携带参数的时候,本质上,都是直接将参数以查询字符串的形式,追加到 URL 地址的后面,发送到服务器的。
编码和解码
- encodeURI() 编码的函数
- decodeURI()解码的函数
- 由于浏览器会自动对 URL 地址进行编码操作,因此,大多数情况下,程序员不需要关心 URL 地址的编码
var str = '像个小丑一样'
var str2 = encodeURI(str)
console.log(str2)
console.log('----------')
var str3 = decodeURI('%E5%83%8F%E4%B8%AA%E5%B0%8F%E4%B8%91%E4%B8%80%E6%A0%B7')
console.log(str3)
使用xhr对象发送POST请求
第一步 还是创建一个xhr对象
const xhr = new XMLHttpRequest()
第二步 调用xhr.open()函数
xhr.open('POST', 'http://www.liulongbin.top:3006/api/getbooks')
第三步 设置Content - Type属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
第四步 调用xhr.send()函数 使其运行 里面写我们需要上传的参数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
第五步 监听 xhr.onreadystatechange事件
xhr.onreadystatechange = function() {
if (xhr.readyState == 4&&xhr.status == 200){
console.log(xhr.responseText);
}
}