XMLHttpRequest是浏览器提供的JS对象,可以请求服务器上传的数据资源
一.使用xhr发起GET请求
一般分为四个步骤:
1.创建xhr对象
2.调用xhr.open()函数
3.调用xhr.send()函数
4.监听xhr.onreadystatechange事件
<script>
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest();
// 2. 调用 open 函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
// 3. 调用 send 函数
xhr.send();
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
//获取服务器响应的数据
console.log(xhr.responseText);
}
}
</script>
二.xhr对象的readyState属性
三.使用xhr发起带参数的GET请求
四.查询字符串
GET请求携带参数的本质
<script>
$.ajax({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
id: 1,
bookname: '西游记'
},
success: function (res) {
console.log(res)
}
})
</script>
五.URL编码与解码
原则:使用英文字符去表示非英文字符
对其进行编码和解码分别是encodeURL( )编码的函数,decodeURL( )解码的函数。
<script>
var str = '黑马程序员'
var str2 = encodeURI(str)
console.log(str2)
console.log('----------')
var str3 = decodeURI('%E9%BB%91%E9%A9%AC')
console.log(str3)
</script>
六.使用xhr发起POST请求
六步:
1.创建xhr对象
2.调用xhr.open()函数
3.设置Content-Type函数(固定写法)
4.调用xhr.send()函数,同时指定要发送的数据
5.监听xhr.onreadystatechange事件
<script>
// 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);
}
}
</script>