IE的JS CORS问题 - 如何解决?

时间:2012-05-17 00:58:18

标签: jquery cross-domain getjson cors

我知道这已经被访问了很多,我已经设法让这个与其他项目一起工作。我继承了这段在IE中不起作用的代码:

function loadTemplate(template, alt_cache_name) {
    if (templates[template] !== undefined) {
        if (alt_cache_name !== undefined) {
            templates[alt_cache_name] = templates[template];
        }
        return templates[template];
    } else {

        return $.get(template, function (response) {
            if (alt_cache_name !== undefined) {
                templates[alt_cache_name] = response;
            }
            templates[template] = response;
        }, 'text');
    }
}

问题在于$ .get()。

template的值是特定html模板的网址。

我尝试了以下操作,但我不认为返回类型与$ .get()返回的类型相同:

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}


function loadTemplate(template, alt_cache_name) {
    if (templates[template] !== undefined) {
        if (alt_cache_name !== undefined) {
            templates[alt_cache_name] = templates[template];
        }
        return templates[template];
    } else {

        var request = createCORSRequest("GET", template);
        var content = "";
        if (request) {
            request.onload = function () {
                //do something with request.responseText
                console.log(request.responseText);
                if (alt_cache_name !== undefined) {
                    templates[alt_cache_name] = response.responseText;
                }
                templates[template] = response.responseText;
            };
        }

        return request;


        //            return $.get(template, function (response) {
        //                if (alt_cache_name !== undefined) {
        //                    templates[alt_cache_name] = response;
        //                }
        //                templates[template] = response;
        //            }, 'text');
    }
}

我甚至尝试了$.get

jQuery.support.cors = true;

有人可以说明如何使其发挥作用吗?

2 个答案:

答案 0 :(得分:0)

事实证明,here列出的jQuery插件可以解决问题。在进一步阅读时,this post也详细说明了解决方案。

- 更新 -

经过进一步测试,IE9和这个库似乎存在一些问题。还有其他人遇到过任何问题吗?

答案 1 :(得分:0)

我有一个类似的问题,我无法在运行时使用IE 8/9上的CORS从CDN加载模板。我可以通过在这里包含xhr-xdr-adapter.js文件来实现它:https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

您可以在需要的地方加入,如下所示:

<!--[if lt IE 10]>
<script src="xhr-xdr-adapter.js" type="text/javascript"></script>
<![endif]-->

xhr-xdr-adapter用不同的函数替换XMLHttpRequest,它在运行时计算出是使用本机XMLHttpRequest还是XDomainRequest。通过包含它,我已经能够使用jQuery和AngularJS进行模板的跨域加载。

相关问题