XMLHttpRequest对象用来在浏览器与服务器之间传送数据。

ajax实现访问文本的简单案例,在服务器环境下:

//创建ajax对象,不兼容IE低版本
 var xhr = new XMLHttpRequest();
 // onreadstatechange指定回调函数,可以动态的监听通信状态(readyState),

 xhr.onreadystatechange = function () {
     //通信状态为4的时候,表示浏览器已经完全接受服务器数据,后者本次接受已失败
     if(xhr.readyState === 4){
         //status 表示http的状态码,200表示正常
         if(xhr.status === 200){
             document.write(xhr.responseText);
         }else{
             document.write(xhr.statusText);
         }
     }
 };
 xhr.onerror = function (e) {
     console.error(xhr.statusText);
 };
 // GET方式, 路径为本地环境下的路径, true表示异步请求,false同步
 xhr.open('GET','./1.txt',true);

 xhr.send(null);
结果

js ajax的实现与应用

下一篇文章ajax的返回数据的类型



相关文章:

  • 2021-09-27
  • 2022-02-04
  • 2022-12-23
  • 2021-10-12
  • 2021-12-03
  • 2022-01-17
  • 2021-12-22
  • 2022-02-19
猜你喜欢
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-03-30
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
相关资源
相似解决方案