ajax请求五个步骤!

今天 咱们讲一讲Ajax请求五个步骤!
1.创建XMLHttpRequest异步对象

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");
  }

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)
    }
  }
}

最后补充一下哈 !

更多推荐

ajax请求五个步骤!