zl程序教程

您现在的位置是:首页 >  前端

当前栏目

ajax请求五个步骤!

AJAX 步骤 请求 五个
2023-06-13 09:11:32 时间

大家好,又见面了,我是你们的朋友全栈君。

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

最后补充一下哈 !

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/145240.html原文链接:https://javaforall.cn