原生js--http请求

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;

posted @ 2014-03-04 09:26  charling  阅读(69994)  评论(0编辑  收藏  举报