首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jquery postcode anywhere api不返回值

jquery postcode anywhere api不返回值
EN

Stack Overflow用户
提问于 2013-11-19 18:53:38
回答 1查看 483关注 0票数 0

我正在使用邮政编码anywhere查找服务,下面的代码允许我通过控制台记录值,但不会将其作为对象返回

代码语言:javascript
运行
复制
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;

            }
        }
    });
}

所以我的电话

代码语言:javascript
运行
复制
   var data = StoreFinder_Interactive_RetrieveNearest_v1_10("xxxxxxxxxxxxx", $('#postcode').val() );
console.log("data is"+data)

提供未定义的数据。

EN

回答 1

Stack Overflow用户

发布于 2013-11-20 22:07:59

这是因为$.getJSON是异步的,在调用下一个函数之前不会立即返回值。

因此,在您的示例中:

代码语言:javascript
运行
复制
var data = StoreFinder_Interactive_RetrieveNearest_v1_10("xxxxxxxxxxxxx", $('#postcode').val() );
console.log("data is"+data)

您的代码将继续使用console.log(),但数据仍未定义,因为StoreFinder函数不会立即返回值。

在javascript中处理这种情况的惯用方法是在StoreFinder函数的参数中包含一个回调函数,该函数将在请求完成后执行。

下面是一个使用$.getJSON的通用示例:

代码语言:javascript
运行
复制
function StoreFinderFunction(options, callback) {
  $.getJSON(options, function(data) {
    // Do what you need to do when you receive the data
    callback(data);
  });
}

然后记录你的结果:

代码语言:javascript
运行
复制
StoreFinderFunction(my_options, function (data) {
  // This will now log your data 
  console.log("data is"+data);
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20069525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档