【问题标题】:jquery postcode anywhere api does not return value任何地方的jQuery邮政编码api不返回值
【发布时间】:2013-12-02 21:16:25
【问题描述】:

我在任何地方使用邮政编码查找服务,下面的代码允许我在控制台记录值,但不将其作为对象返回

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)

给出未定义的数据。

【问题讨论】:

    标签: jquery api return


    【解决方案1】:

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

    所以,在你的例子中:

    var data = StoreFinder_Interactive_RetrieveNearest_v1_10("xxxxxxxxxxxxx", $('#postcode').val() );
    console.log("data is"+data)
    

    由于您的 StoreFinder 函数不会立即返回值,因此您的代码将移至 console.log(),但数据仍未定义。

    在 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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多