js ajax的实现与应用

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);
结果


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



发布了31 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_38694034/article/details/79174487