• 技术文章 >web前端 >js教程

    如何实现AJAX请求?

    GuanhuiGuanhui2020-06-24 15:31:05原创1015

    如何实现AJAX请求?

    1、创建XMLHttpRequest实例;

    var xhr;if(window.XMLHttpRequest) {
      //ie7+,firefox,chrome,safari,opera
      xhr = new XMLHttpRequest();}else {
      //ie5,ie6
      xhr = new ActiveXObject("Microsoft.XMLHTTP");}

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

    xhr.onreadystatechange = function() {
      if(xhr.readyState==4 && xhr.status==200) {
        console.log(xhr.responseText);
      }}

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

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

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

    xhr.send(null);

    完整代码

    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请求?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:ajax js
    上一篇:Vue中如何正确强制组件重新渲染?(方法介绍) 下一篇:JavaScript 中 setTimeout 函数怎么用?
    大前端线上培训班

    相关文章推荐

    • 为什么vue不使用ajax• Ajax 是干嘛用的?• Ajax接收JSON数据• PHP如何结合AJAX删除数据?

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网