我正在使用邮政编码anywhere查找服务,下面的代码允许我通过控制台记录值,但不会将其作为对象返回
function StoreFinder_Interactive_RetrieveNearest_v1_10(Key, Origin, MaximumItems, MaximumRadius, MaximumTime, DistanceType, LocationLists) {
$.getJSON("http://services.postcodeanywhere.co.uk/StoreFinder/Interactive/RetrieveNearest/v1.10/json3.ws?callback=?",
{
Key: Key,
Origin: Origin,
MaximumItems: MaximumItems,
MaximumRadius: MaximumRadius,
MaximumTime: MaximumTime,
DistanceType: DistanceType,
LocationLists: LocationLists
},
function (data) {
// Test for an error
if (data.Items.length == 1 && typeof(data.Items[0].Error) != "undefined") {
// Show the error message
alert(data.Items[0].Description);
}
else {
// Check if there were any items found
if (data.Items.length == 0)
alert("Sorry, there were no results");
else {
// PUT YOUR CODE HERE
//FYI: The output is a JS object (e.g. data.Items[0].YourId), the keys being:
distance = data.Items[0].Distance;
console.log(distance);
// name = data.Items[0].Name;
//YourId
//Name
//Description
//Distance
//Time
//Easting
//Northing
//Latitude
//Longitude
return distance;
}
}
});
}
所以我的电话
var data = StoreFinder_Interactive_RetrieveNearest_v1_10("xxxxxxxxxxxxx", $('#postcode').val() );
console.log("data is"+data)
提供未定义的数据。
发布于 2013-11-20 22:07:59
这是因为$.getJSON是异步的,在调用下一个函数之前不会立即返回值。
因此,在您的示例中:
var data = StoreFinder_Interactive_RetrieveNearest_v1_10("xxxxxxxxxxxxx", $('#postcode').val() );
console.log("data is"+data)
您的代码将继续使用console.log(),但数据仍未定义,因为StoreFinder函数不会立即返回值。
在javascript中处理这种情况的惯用方法是在StoreFinder函数的参数中包含一个回调函数,该函数将在请求完成后执行。
下面是一个使用$.getJSON的通用示例:
function StoreFinderFunction(options, callback) {
$.getJSON(options, function(data) {
// Do what you need to do when you receive the data
callback(data);
});
}
然后记录你的结果:
StoreFinderFunction(my_options, function (data) {
// This will now log your data
console.log("data is"+data);
});
https://stackoverflow.com/questions/20069525
复制相似问题