首页 > Web开发 > 详细

原生js--http请求

时间:2014-03-04 20:44:24      阅读:692      评论:0      收藏:0      [点我收藏+]

1、终止请求和超时

终止请求XMLHttpRequest对象提供abort方法,调用该方法时触发abort事件

XHR2提供了timeout属性,当超时发生时触发timeout事件。但浏览器尚不支持自动超时。可以使用setTimeout模拟实现。

例如:

function timedGetText( url, time, callback ){
    var request = new XMLHttpRequest();
    var timeout = false;
    var timer = setTimeout( function(){
        timeout = true;
        request.abort();
    }, time );
    request.open( "GET", url );
    request.onreadystatechange = function(){
        if( request.readyState !== 4 ) return;
        if( timeout ) return;
        clearTimeout( timer );
        if( request.status === 200 ){
            callback( request.responseText );
        }
    }
    request.send( null );
}

2、跨域HTTP请求

XHR2通过在HTTP响应中选择发送合适的CORS(Cross-Origin Resource Sharing),允许跨域访问网站,Firefox、Chrome等都已经支持CORS,IE8通过SDomainRequest对象支持。但这种跨域请求不会包含cookie和HTTP身份验证令牌,可以通过设置withCredentials为true才能实现包含以上信息。

 

3、借助script发送HTTP请求(jsonp)

支持jsonp的服务不会强制指定客户端必须实现的回调函数名称

使用script元素发送JSON请求

function getJSONP( url, callback ){
    var cbnum = "cb" + getJSONP.counter++;
    var cbname = "getJSONP." + cbnum;
    if( url.indexOf( "?" ) === -1 ){
        url += "?jsonp=" + cbname;
    }else{
        url += "&jsonp" + cbname
    }
    var script = document.createElement( "script" );
    // 回调函数
    getJSONP[cbnum] = function( response ){
        try{
            callback( response );
        }finally{
            delete getJSONP[num];
            script.parentNode.removeChild( script );
        }
    };
    script.src = url;
    document.body.appendChild( script );
}
getJSONP.counter = 0;

原生js--http请求,布布扣,bubuko.com

原生js--http请求

原文:http://www.cnblogs.com/charling/p/3579704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!