使用XMLHttpRequest对象向服务器发起请求


使用xhr发起GET请求

  1. 创建xhr对象

    var xhr = new XMLHttpRequest();
  2. 调用xhr.open()函数

    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
  3. 调用xhr.send()函数

    xhr.send();
  4. 监听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()解码函数

声明:极客角度|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - 使用XMLHttpRequest对象向服务器发起请求


拒绝拖延,勇于表达!