AJAX请求

AJAX: Asyncchronous Javascript + XMLL

XMLHttpRequest对象(XHR)

以异步的方式从服务器获取数据,获取新数据后,通过DOM的方式将新数据插入到页面中。

1. 新建XHR对象

  • IE7+、现代浏览器d都支持原生的XHR对象

var xhr = new XMLHttpRequest();

2. open(method, url, boolean)

  • method: 发送请求的类型(get、post、delete、put等)
  • url: 请求URL(相对路径是相对于当前页面或者绝对路径)
  • boolean: 是否异步发送请求

3. send():一个参数,作为请求主体发送的数据,或者为null

收到相应请求后,响应数据会自动填充XHR对象的属性。

  • responseTetx 作为响应主体被返回的文本。
  • responseXML 响应类型是text/xml或者application/xml,保存包含响应数据的XML DOM文档。
  • status HTTP响应状态
  • statusText HTTP响应状态说明

4. 同步方式请求

var xhr = new XMLHttpRequest();
xhr.open('get', 'example.json', false);
xhr.send(null);

if((xhr.status > 200 && xhr.status < 300) || xhr.status == 304){
        //xhr.responseText;
        //通过检测xhr.status来检测请求返回状态,不要依赖statusText,因为跨浏览器时statusText不可靠
}else{
        //请求错误, 输出错误log:xhr.status
}

5. 异步方式请求

异步请求,检测XHR对象的<code>readyState</code>属性,该属性表示请求/响应过程中的当前活动阶段。

  • 0 : 未初始化。尚未调用open()方法。
  • 1 : 启动。已经调用open()方法, 但未调用send()方法。
  • 2 : 发送。已经调用send()方法, 但未接收到响应。
  • 3 : 接收。已经接收到部分响应数据。
  • 4 : 完成。已经接收到全部响应数据,已经可以在客户端使用。

readyState值变化都会触发readystatechange时间

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if(xhr.readyState == 4){
    if(xhr.status > 200 && xhr.status < 300 || xhr.status == 304){
      alert(xhr.reponseText);
    }else{
      alert("Request was unsuccessful: " + xhr.status);
  }
}
xhr.open('get', 'example.json', true);
xhr.send(null);

6. 取消异步请求

xhr.abort()

7.HTTP头部信息

  • Accept 浏览器处理的内容类型
  • Accept-Charset 显示的字符集
  • Accept-Econding 处理的压缩编码
  • Connection 与服务器之间的连接类型
  • Cookie Cookie设置
  • Host 发出请求所在的域
  • Referer 发出请求坐在的URI

xhr.setRequestHeader('HeaderName', 'HeaderVal'); 使用自定义的头部字段名称,有些浏览器禁止修改默认的头部字段 。
xhr.getResponseHeader('HeaderName');
xhr.getAllResponseHeaders();


function create_connect_obj(){
    if(window.ActiveXObject!='undefined' && window.ActiveXObject!=undefined){
        return new ActiveXObject('Microsoft.XMLHTTP');
    }else if(window.XMLHttpRequest!='undefined' && window.XMLHttpRequest!=undefined){
        return new XMLHttpRequest();
    }
}

var doget=function(url,data,success,fail){
    var conn=create_connect_obj();
    if(typeof(data)=='object'){
        var str='';
        for(var i in data){
            str+='&'+i+'='+data[i];
        }
        str=str.substr(1);
        if(url.indexOf('?')!=-1){
            url+=str;
        }else{
            url+='?'+str;
        }
    }else if(typeof(data)=='string'){
        if(url.indexOf('?')!=-1){
            url+=data;
        }else{
            url+='?'+data;
        }
    }
    conn.open('GET',url);
    conn.send(null);
    conn.onreadystatechange=function(){
        if(conn.readyState==4 && conn.status==200){
            if(typeof(data)=='function'){
                data(conn.response);
            }else if(typeof(success)=='function'){
                success(conn.response); //success
            }
        }else{
            if(typeof(fail)=='function'){   //fail
                fail(); 
            }
        }
    }
}

var dopost=function(url,data,success,fail){
    var conn=create_connect_obj();
    conn.open('POST',url);
    conn.setRequestHeader('Content-type','application/x-www-form-urlencoded');

    if(typeof(data)=='object'){
        var str='';
        for(var i in data){
            str+='&'+i+'='+data[i];
        }
        str=str.substr(1);
        conn.send(data);
    }else if(typeof(data)=='string'){
        conn.send(data);
    }else{
        conn.send(null);
    }
    conn.onreadystatechange=function(){
        if(conn.readyState==4 && conn.status==200){
            if(typeof(data)=='function'){
                data(conn.response);
            }else if(typeof(success)=='function'){
                success(conn.response); //success
            }
        }else{
            if(typeof(fail)=='function'){   //fail
                fail(); 
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,399评论 19 139
  • Ajax和XMLHttpRequest 我们通常将Ajax等同于XMLHttpRequest,但细究起来它们两个是...
    changxiaonan阅读 6,771评论 0 2
  • AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 X...
    源大侠阅读 3,564评论 0 1
  • ajax 的全称是Asynchronous JavaScript and XML,其中,Asynchronous ...
    呼呼呼lys阅读 5,199评论 0 4
  • 92年的我,在这里为大家讲述,本人从零打造一百万的真实经历。 2014年,是我开始改变的第一年。踏入22年,我顺利...
    深山小牧童阅读 4,597评论 0 1