首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >任何模拟*同步* XDomainRequest (XDR)请求的方法

任何模拟*同步* XDomainRequest (XDR)请求的方法
EN

Stack Overflow用户
提问于 2013-08-30 21:51:38
回答 1查看 2.6K关注 0票数 3

我们正在对谷歌地图、地理代码API进行跨域调用。在现代浏览器中,这过去和现在都很不错,但在IE8中根本不起作用。看起来它在IE9中也会失败(部分CORS支持)。这导致包括一个XDomainRequest (XDR)来照顾IE8-9.这样做在我的独立测试中效果很好,可以在IE8中获得数据。

我现在遇到的问题是XDR只能异步工作,所以我的地理代码函数在我的xdr.onload触发之前返回。

在我的搜索函数中,我调用了geocode函数:

代码语言:javascript
复制
var location = Geocode(city, state);

if (!location) {
    alert('Unable to determine the location of the city and state you entered');
    StopLoading();
    return;
}
//function then uses location.lat and location.lng coordinates

在IE8中,我点击了上面的“无法确定位置”警报。

这是我的地理编码函数:

代码语言:javascript
复制
Geocode = function (address, state) {
var protocol = location.protocol,
    url = '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address=',
    param = encodeURIComponent(address + ', ' + state),
    json = {};

if ('XDomainRequest' in window && window.XDomainRequest !== null) {
    //IEs that do not support cross domain xhr requests
    var xdr = new XDomainRequest();

    xdr.open('get', protocol + url + param);
    xdr.onload = function() {
        json = jQuery.parseJSON(xdr.responseText);
    };
    xdr.send();
} else {
    //good browsers
    jQuery.ajax({
        url: protocol + url + param,
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data) {
            json = data;
        }
    });
}

//alert(json);
if (json.status !== 'OK') {
    alert('Unable to determine the location of the city and state you entered');
    return null;
}

return json.results[0].geometry.location;
};

如果我在geocode函数中注释掉警报( json ),我将在IE8中获得结果,因为这是一个阻塞操作,因此请求有时间完成并填充json对象。当它在未注释的情况下运行时,json对象就不会被填充。

有人知道我如何在IE中工作吗?

EN

回答 1

Stack Overflow用户

发布于 2013-08-30 22:06:45

异步就是异步。如果您想在请求完成后执行某些操作,则必须将其放入xdr.onload函数中。

javascript中没有“等待”函数。您可以构建一个变量并执行一个setTimeout循环来检查变量的所有x毫秒。但在这种情况下,这对你没有帮助(而且它非常丑陋)。在您的情况下,您可以使用onerror和ontimeout来检查服务器是否有问题,使用onload来检查城市是否在json中。

代码语言:javascript
复制
xdr.onload = function() {
json = jQuery.parseJSON(xdr.responseText);
//check if a city is loaded, go on if true
};
xdr.onerror = function() {
alert('Unable to determine the location of the city and state you entered');
//do whatever u wanna do if something went wrong
xdr.ontimeout = function() {
alert('404 Server');
//do whatever u wanna do if something went wrong
}

我希望这能帮助您找到方法(顺便说一句,异步请求的使用比阻止javascript/browser漏洞要好得多;)

jQuery医生说:

在jQuery 1.8中,异步: false with jqXHR ($.Deferred)的用法已被废弃;您必须使用成功/错误/完全回调选项,而不是使用jqXHR对象的相应方法,如jqXHR.done()或不推荐的jqXHR.success()。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18541977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档