使用XMLHttpRequest发送网络请求

使用XMLHttpRequest发送get请求

步骤

  1. 创建xhr对象
  2. 调用xhr.open()函数
  3. 调用xhr.send函数
  4. 监听onreadystatechange事件
    未携带参数的get请求
var xhr = new XMLHttpRequest();
xhr.open("get","http://127.0.0.1:8000");
xhr.send();
xhr.onreadystatechange = function() {
   
    if(xhr.readyState === 4 && xhr.status ===200){
   
        console.log(xhr.responseText);
    }
}
xhr.onerror = function (error) {
   
    console.log(error)
};

携带参数的get请求

var xhr = new XMLHttpRequest();
xhr.open("get","http://127.0.0.1:8000?name=js&age=18");
xhr.send();
xhr

你可能感兴趣的:(计算机网络,网络,javascript,前端)