![](/img/trans.png)
[英]Display please wait or a loader using javascript- REST API call
[英]Data Cant Display in Rest API call by Javascript
我在Javascript中使用rest API,对gepcoding使用Jquery。 在这段代码中,我无法从xmlhttp.onreadystatechange = function()
函数获取数据
我的代码可以从Google API获取数据
var postdata = '{"cellTowers":[{"cellId": '+cid+',"locationAreaCode": '+lac+',"mobileCountryCode": '+mcc+',"mobileNetworkCode": '+mnc+'}]}'
xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=YOURKEY";
xmlhttp.open('POST',url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(postdata);
var lat;
var lng;
var data = '';
var json;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText)
{
var data = xmlhttp.responseText;
var json = JSON.parse(data);
lat = json.location.lat;
lng = json.location.lng;
alert(lat+""+lng); //Working [1 operation]
}
}
};
alert(lat+""+lng); //Not Working [2 operation]
在此代码中,我试图从xmlhttp.onreadystatechange = function()
函数中获取postdata,但是我得到了空值。 因为当我运行程序时,我先看到[2操作]操作,然后再看到[1操作]
我的代码有问题吗? 或给我关于这个问题的建议。 或可以使用任何其他方式使用该API
您的代码工作正常。 事件发生时,函数将异步运行。 在从远程API返回答案之前执行2次操作是正常的。 请让我知道是什么让您不高兴。 代码很好,可以按预期工作,可以从远程API获得答案。 答案只能在函数内部接收,然后就应该继续调用后续代码,就像从那里开始应用逻辑一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.