使用javascript提取json数组数据
我想使用javascript从以下查询字符串返回的json数据中获取格式化的_地址使用javascript提取json数组数据,javascript,arrays,json,geocode,reversegeocodelocation,Javascript,Arrays,Json,Geocode,Reversegeocodelocation,我想使用javascript从以下查询字符串返回的json数据中获取格式化的_地址 我尝试获取格式化的\u地址,但它返回未定义的地址。您可以获得这样的格式化地址(Ajax成功) 抱歉,我之前的回复只修复了AJAX请求- 在请求上指定contentType不是必需的,也没有影响-这由服务器控制 jQuery已经将请求解析为一个对象,调用JSON。响应上的stringify导致该对象被解析为JSON格式的字符串,删除该行解决了问题。另外,指定数据类型似乎没有必要 值得注意的是,您正在向函数传递la
我尝试获取格式化的\u地址,但它返回未定义的地址。您可以获得这样的格式化地址(Ajax成功)
抱歉,我之前的回复只修复了AJAX请求- 在请求上指定contentType不是必需的,也没有影响-这由服务器控制 jQuery已经将请求解析为一个对象,调用
JSON。响应上的stringify
导致该对象被解析为JSON格式的字符串,删除该行解决了问题。另外,指定数据类型似乎没有必要
值得注意的是,您正在向函数传递lat和lng参数,但没有使用它们-我建议添加如下行:
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
下面是一个完整的解决方案,包括我的建议:
function getReverseGeocodingData(lat, lng) {
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
jsondata = {};
//use ajax and json
$.ajax({
type: "POST",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + sessionStorage.latitude + "," + sessionStorage.longitude + "&sensor=true",
data: jsondata,
success: function (response) {
var address = response.results[0].formatted_address;
var error = response.Error;
if (address != null) {
alert("Found current location: " + address);
sessionStorage.currentAddress = address;
}
},
error: function (msg) {
errorConnection();
}
});
}
只需更改成功函数,您将获得所有格式化的地址
success: function (response) {
var address = response.results;
var error = response.error; //write exact word of the "error" which you get in response
if(address.length > 0) {
for(i=0; i<address.length; i++) {
console.log("Found current location: " + address[i].formatted_address);
}
}
},
成功:功能(响应){
var地址=response.results;
var error=response.error;//写出您在响应中得到的“error”的确切单词
如果(address.length>0){
对于(i=0;i有一些问题需要解决:
显然,您不必在发出GET
请求时发布数据
我重写了您的代码,从lat
和lng
获取参数,以便轻松测试
response
是一个包含结果
对象数组(小写r
复数)的对象。每个对象都包含一个格式化的\u地址
属性
您很可能希望获取第一个:
response.results[0]。格式化的\u地址
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax(
{
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true",
dataType: "json",
success: function (response) {
alert("Found current location: " + response.results[0].formatted_address);
},
error: function (msg) {
alert('error');
}
});
}
要尝试它:
getReverseGeocodingData(44.4647452,7.3553838);
产出:
找到当前位置:Via Pasubio,34,12025 Dronero CN,Italia
抱歉,我之前只使用我的答案解决了ajax问题-我已更新了我的答案以修复剩余的问题谢谢Brian的帮助。var address=response.results[0]
有关更多详细信息,请参阅我的答案谢谢你的帮助。谢谢你的帮助。谢谢你的帮助。谢谢你的帮助。
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax(
{
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true",
dataType: "json",
success: function (response) {
alert("Found current location: " + response.results[0].formatted_address);
},
error: function (msg) {
alert('error');
}
});
}
getReverseGeocodingData(44.4647452,7.3553838);