如何实现AJAX请求?


本文摘自PHP中文网,作者Guanhui,侵删。

如何实现AJAX请求?

1、创建XMLHttpRequest实例;

1

2

3

4

5

var xhr;if(window.XMLHttpRequest) {

  //ie7+,firefox,chrome,safari,opera

  xhr = new XMLHttpRequest();}else {

  //ie5,ie6

  xhr = new ActiveXObject("Microsoft.XMLHTTP");}

2、监听readystatechange事件,并通过readyState属性来判断请求状态;

1

2

3

4

xhr.onreadystatechange = function() {

  if(xhr.readyState==4 && xhr.status==200) {

    console.log(xhr.responseText);

  }}

3、调用open()方法指定请求类型和地址;

1

xhr.open("GET", "xhr_info.txt");

4、调用send()方法发送请求即可。

1

xhr.send(null);

完整代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

var xhr;

if(window.XMLHttpRequest) {

  //ie7+,firefox,chrome,safari,opera

  xhr = new XMLHttpRequest();

} else {

  //ie5,ie6

  xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.onreadystatechange = function() {

  if(xhr.readyState==4 && xhr.status==200) {

    console.log(xhr.responseText);

  }

}

xhr.open("GET", "xhr_info.txt", true);

xhr.send(null);

推荐教程:《JS教程》

以上就是如何实现AJAX请求?的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

js中隐藏元素用什么方法

history解决ajax出现的问题

前端工程师需要掌握哪些知识?

js如何修改注册表

web前端js是什么

js实现页面跳转的方法

带你轻松理解kmp算法

ajax和javascript区别是什么

web学习之怎么使用纹理贴图

js获取html元素的实际宽度高度的方法

更多相关阅读请进入《ajax》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...