ajax请求的五个步骤

  1. 创建XMLHttpRequest异步对象

    var xhr = new XMLHttpRequest()
    
  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)
        }
      }
    }
    
posted @ 2019-07-23 15:16  0x29a  阅读(11467)  评论(0编辑  收藏  举报