使用xhr发起GET请求
创建xhr对象
var xhr = new XMLHttpRequest();
调用xhr.open()函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
调用xhr.send()函数
xhr.send();
监听xhr.onreadystatechange事件
xhr.onreadystatechange = function() { // 监听 xhr 对象的请求状态 readyState;与服务器响应的状态 status if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } }
使用xhr发起带参数的GET请求
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1');
// URL地址后面拼接的参数,叫做查询字符串
// 查询字符串格式: ?放在URL的末尾,然后再加上参数=值,多个参数用&进行分隔。
使用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-wwww-form-urlencoded');
// 4.调用send函数
xhr.send('book=水浒传&author=施耐庵&publisher=天津图书出版社');
// 5.监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
对URL编码与解码
encoedURL()
编码函数decoedURL()
解码函数
Comments | NOTHING