XMLHttpRequest发请求的步骤

发布时间 2023-04-28 16:58:18作者: *感悟人生*
/*具体来说,AJAX 包括以下几个步骤。
 以下是AJAX发请求的步骤
  1. 创建 XMLHttpRequest 实例
  2. 发出 HTTP 请求
  3. 接收服务器传回的数据
  4. 更新网页数据
  */


//实例化一个对象 xhr
var xhr = new XMLHttpRequest(),
    method ="GET",
    url ="https://www.baidu.com/";

//一旦新建实例,就可以使用`open()`方法指定建立 HTTP 连接的一些细节。
xhr.open(method,url,true);
xhr.onreadystatechange =function (){
    if(xhr.readyState===XMLHttpRequest.D0NE && xhr.status===200) {
        console.log(xhr.responseText)
    }
}
// 上面代码中,一旦`XMLHttpRequest`实例的状态发生变化,就会调用监听函数`handleStateChange`
// 最后使用`send()`方法,实际发出请求。
//发包
xhr.send();