$.getScript
即使在移动设备已连接互联网的情况下也无法工作。我们如何为下面的代码编写jquery.getscript?我无法在脚本中加载我的url,因为如果移动设备没有互联网,我的应用程序不会启动,所以如果互联网连接可用,我想包括我的url。有人能纠正我的代码吗?
if (states[networkState] == 'No network connection') {
// Device with no network data connection
document.getElementById("location").innerHTML = "Location unavailable";
} else {
// code for getting current address using Lat/Longs
$.getScript("https://maps.googleapis.com/maps/api/js?sensor=true", function () {
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add = results[0].formatted_address;
document.getElementById("location").innerHTML = "Location : " + add;
} else {
document.getElementById("location").innerHTML = "No Results found ";
}
} else {
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
alert("Geocoder failed due to: " + status);
}
});
});
}
更新:
实际上,这里底层的东西是行不通的。谷歌很聪明。。。回复是空的,但他们更聪明。。。如果您查看他们的API文档,您可以看到他们允许您在请求中指定回调。所以你会这样做:
jQuery('body').append('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=address"/>')
注意参考callback=address
故事的寓意是阅读API文档:D
我假设但没有奏效的东西:
它之所以失败,是因为有些东西还没有定义。但是,如果你查看返回的脚本,你会发现它正在从https://maps.gstatic.com/intl/en_us/mapfiles/api-3/15/4/main.js.
你可以:
在
$.getScript()
回调中加载该脚本,然后在回调中调用地址函数。由于上面的URL可能是动态生成的,您可能需要使用regex来解析第一个getScript响应,然后从该响应中提取URL以进行回调。您应该考虑在这里使用
$.ajax
而不是$.getScript
,这样您就可以使用cache
结果,否则它每次都会使用一个随机数来重新请求新的脚本。或者你可以考虑在回调中使用计时器来寻找新变量或对象的存在,以知道它已经完成了加载(无论它之前失败了什么)