zoukankan      html  css  js  c++  java
  • 【ajax】xhr

    jQuery

    xhr: function() {
        return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    }

    JavaScript框架设计

    // 缓存
    function xhr() {
        if (!xhr.cache) {
            var fns = [
                function () { return new XMLHttpRequest(); },
                function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
                function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
            ];
            for (var i = 0, n = fns.length; i < n; i++) {
                try {
                    fns[i]();
                    xhr.cache = fns[i];
                    break;
                } catch(e) {}
            }
            return xhr.cache();
        } else {
            return xhr.cache();
        }
    }
    
    var xhrObject = xhr(); //调用
    alert(xhrObject) //[object XMLHttpRequest]
    var xhr = function() {
        var fns = [
            function () { return new XMLHttpRequest(); },
            function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
            function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
        ];
        for (var i = 0, n = fns.length; i < n; i++) {
            try {
                fns[i]();
                xhr = fns[i];//注意这里,覆写自身
                break;
            }catch(e) {}
        }
        return xhr()
    }
    
    console.log(xhr)
    console.log(xhr())
    console.log(xhr)
    console.log(xhr())

    window.$ = {}
    var s = ["XMLHttpRequest", "ActiveXObject('Msxml2.XMLHTTP.6.0')","ActiveXObject('Msxml2.XMLHTTP.3.0')", "ActiveXObject('Msxml2.XMLHTTP')"];
    if (!"1"[0]) {
        //判定IE67
        s[0] = location.protocol === "file:" ? "!" : s[0]; // 报异常,跳过
    }
    for (var i = 0, axo; axo = s[i++]; ) {
        try {
            if (eval("new " + axo)) {
                $.xhr = new Function("return new " + axo);
                break;
            }
        } catch (e) {}
    }

    我们再认真思考一下,既然我们是写框架,那么这些检测其实是放在 IIFE 里面,因此基本不用覆写,检测好哪个可用,就把它加到命名空间上就好了。最后的版本就出来了,使用new Function、eval,反正只用一次,耗不了多少性能

  • 相关阅读:
    JavaScript打印99乘法表
    Python列表推导式玩法
    Python错误重试方法
    pandas + jupyter进行数据处理
    新手小白的爬虫神器-无代码高效爬取数据
    Adb连接模拟器出现版本错误
    Python发送多人邮件报错
    Django入门
    git clone 下载速度解决办法
    Python实现自动刷抖音
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5887439.html
Copyright © 2011-2022 走看看