zoukankan      html  css  js  c++  java
  • 原生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;

  • 相关阅读:
    Mac上的USB存储设备使用痕迹在新版操作系统有所变化
    Beware of the encrypted VM
    A barrier for Mobile Forensics
    Second Space could let suspect play two different roles easily
    Take advantage of Checkra1n to Jailbreak iDevice for App analysis
    Find out "Who" and "Where"
    Where is the clone one and how to extract it?
    Downgrade extraction on phones running Android 7/8/9
    高版本安卓手机的取证未来
    How to extract WeChat chat messages from a smartphone running Android 7.x or above
  • 原文地址:https://www.cnblogs.com/charling/p/3579704.html
Copyright © 2011-2022 走看看