简体   繁体   English

Javascript跨域请求在IE8中

[英]Javascript Cross domain requests in IE8

I have a function that verifies an ID against a database. 我有一个功能,可以根据数据库验证ID。 If the ID is found, the function returns true and if not it returns false. 如果找到ID,则该函数返回true,否则返回false。

Got the request to work in the other browsers. 得到了在其他浏览器中工作的请求。 Now working on figuring it out with Internet Explorer's XDomainRequest. 现在正在使用Internet Explorer的XDomainRequest进行计算。

function verify(id){
    xmlhttp=new window.XDomainRequest();
    xmlhttp.onload = checkResponse;
    xmlhttp.open("GET", "http://abc.com/verify?id=" + encodeURIComponent(id));
    xmlhttp.send();

    function checkResponse(){
        if(xmlhttp.responseText == 200) {   
            return true;
        } else {
            return false;
        }
    }
}

The problem is that I want the verify function to return false, not the checkResponse function. 问题是我希望验证函数返回false,而不是checkResponse函数。

In other browsers setting the open to false does the trick but not in IE. 在其他浏览器中将open设置为false可以解决问题,但不能在IE中使用。

No jQuery answers please. 请不要jQuery回答。

Thanks for your help! 谢谢你的帮助!

Here is the recommended way to incorporate CORS requests in IE8 into jQuery. 以下是将IE8中的CORS请求合并到jQuery中的推荐方法。 You could probably use this as a starting point for your own: 您可以将此作为自己的起点:

https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js

Also, verify shouldn't be a synchronous operation. 此外, verify不应该是同步操作。 Would recommend passing a callback function to it and keeping it async: 建议将回调函数传递给它并保持异步:

function verify(id, callback){
    var xmlhttp = new window.XDomainRequest();
    xmlhttp.onload = function () {
        callback( xmlhttp.responseText === 200 );
    };
    xmlhttp.open("GET", "http://abc.com/verify?id=" + encodeURIComponent(id));
    xmlhttp.send();
}

Which you could then call like so: 你可以这样打电话:

verify( 123456, function ( isValid ) {
    if ( isValid ) {
        // do something if valid
    } else {
        // or not
    }
});

the first point you need to consider is changing you js code to work as non asynchronous. 您需要考虑的第一点是将js代码更改为非异步。 Otherwise the checkResponse is the only point you have to get an answer. 否则checkResponse是你必须得到答案的唯一一点。 Your code seems to be asynchronous, and it should be synchronous. 您的代码似乎是异步的,它应该是同步的。

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM