jquery почтовый индекс нигде api не возвращает значение

0

Я использую почтовый индекс для поиска в любом месте, код ниже позволяет мне консольно регистрировать значение, но не возвращает его как объект

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)

дает данные как неопределенные.

Теги:
return

1 ответ

1

Это связано с тем, что $.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);
});

Ещё вопросы

Сообщество Overcoder
Наверх
Меню