【发布时间】:2013-08-30 21:51:38
【问题描述】:
我们正在对 google maps geocode API 进行跨域调用。这在现代浏览器中过去和现在都很好,而且在现代浏览器中运行良好,但在 IE8 中根本不起作用。看起来它在 IE9 中也会失败(部分 CORS 支持)。这导致包含一个 XDomainRequest (XDR) 来处理 IE8-9。在我的独立测试中这样做可以很好地在 IE8 中获取数据。
我现在遇到的问题是 XDR 只能异步工作,所以我的地理编码函数在我的 xdr.onload 触发之前返回。
在我的搜索功能中,我调用了地理编码功能:
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 中点击了上面的“无法确定位置”警报。
这是我的地理编码功能:
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;
};
如果我在地理编码函数中注释掉 alert(json),我会在 IE8 中得到结果,因为这是一个阻塞操作,因此请求有时间完成并填充我的 json 对象。当它在未注释的情况下运行时,不会填充 json 对象。
有人知道如何在 IE 中使用它吗?
【问题讨论】:
-
为什么不让你的代码异步兼容呢?它将具有 #1 在 oldie 中工作的好处,并且 #2 在获取地理位置数据时不会导致浏览器看起来像是坏了。
-
也许这是我在画一个空白的地方,因为我尝试在我的 onload 和 success 回调中调用一个函数。该函数在地理编码中,并且只是在上述地理编码函数的末尾具有逻辑。地理编码功能仍在 IE 中返回,没有 json obj/data,因此我的搜索功能仍在点击“无法确定位置”警报。也许我会在周末发布一个工作小提琴/bin,基本上重新发布指向工作代码的问题。
标签: javascript jquery json synchronous xdomainrequest