1. 创建XMLHttpRequest异步对象
步骤一代码引自:https://www.w3school.com.cn/ajax/ajax_xmlhttprequest_create.asp
var xhr;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xhr=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
图片引自:https://www.cnblogs.com/hyj0608/p/6726852.html?utm_source=itdadao&utm_medium=referral
主流创建ajax对象的方法:
 IE6以下版本浏览器创建ajax对象方法是:
2. 设置回调函数
xhr.onreadystatechange = callback
 
3. 使用open方法与服务器建立连接
// get 方式
xhr.open("get", "test.php", true)
// post 方式发送数据 需要设置请求头
xhr.open("post", "test.php", true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
 
4. 向服务器发送数据
// get 不需要传递参数
xhr.send(null)
// post 需要传递参数
xhr.send("name=jay&age=18")
 
5. 在回调函数中针对不同的响应状态进行处理
function callback() {
  // 判断异步对象的状态
  if(xhr.readyState == 4) {
    // 判断交互是否成功
    if(xhr.status == 200) {
      // 获取服务器响应的数据
      var res = xhr.responseText
      // 解析数据
      res = JSON.parse(res)
    }
  }
}
 
补充
| 属性 | 描述 | 
|---|---|
| onreadystatechange | 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 | 
| readyState | 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 | 
| - | 0: 请求未初始化 | 
| - | 1: 服务器连接已建立 | 
| - | 2: 请求已接收 | 
| - | 3: 请求处理中 | 
| - | 4: 请求已完成,且响应已就绪 | 
| status | 200: “OK” 404: 未找到页面 | 
                    
                
                
            
        
浙公网安备 33010602011771号