创建XMLHttpRequest异步对象 主流创建ajax对象的方法: IE6以下版本浏览器创建ajax对象方法是: 设置回调函数 xhr.onreadystatechange = callback // onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。使用open方法与服务器建立连接 // get 方式 xhr.open(“get”, “test.php”, true) // post 方式发送数据 需要设置请求头 xhr.open(“post”, “test.php”, true) xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)向服务器发送数据 // get 不需要传递参数 xhr.send(null) // post 需要传递参数 xhr.send(“name=jay&age=18”)在回调函数中针对不同的响应状态进行处理 function callback() { // 判断异步对象的状态 if(xhr.readyState == 4) { // 判断交互是否成功 if(xhr.status == 200) { // 获取服务器响应的数据 var res = xhr.responseText // 解析数据 res = JSON.parse(res) } }}
注解:
readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4: 请求已完成,且响应已就绪
status 200: “OK” 404: 未找到页面
参考:https://www.cnblogs.com/tfxz/p/12701681.html