Explorer中创建跨域XMLHTTP请求

Explorer中创建跨域XMLHTTP请求

本文介绍了如何在Internet Explorer中创建跨域XMLHTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码看起来像这样,建议IE工作,但它只适用于Chrome和FF。是否有正确的方法从其他域访问URL。此外,域名是我拥有的域名,可以允许访问尝试访问它的脚本:

My code looks like this, which is recommended for IE to work, but it only works in Chrome and FF. Is there a correct way to access a url from another domain. Furthermore, the domain is a domain I own and can allow access to the scripts trying to access it:

<script language="javascript" type="text/javascript">
function sendRequest(url,callback,postData) {
    var req = createXMLHTTPObject();
    if (!req) return;
    var method = (postData) ? "POST" : "GET";
    req.open(method,url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
        req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//          alert('HTTP error ' + req.status);
            return;
        }
        callback(req);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

function handleRequest(req) {
    var MyResponse = req.responseText;
    document.open();
    document.write(MyResponse);
    document.close();
}

 sendRequest("http://anotherdomain.com/urlwithcontentneeded.php",handleRequest);


</script>


推荐答案

IE不以这种方式支持跨域请求但是确实有办法使用XDomainRequest对象,请参阅

IE does not suppoort cross domain requests in this way but does have a way using the XDomainRequest object instead, see http://msdn.microsoft.com/en-us/library/cc288060(v=vs.85).aspx

它的工作原理大致相同然而,是的,这是一种痛苦,有两种方法可以在不同的浏览器中做到这一点

It works in much the same way though, and yes it's a pain there are two ways to do it in different browsers

这篇关于如何在Internet Explorer中创建跨域XMLHTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:47