簡體   English   中英

無法從我的API調用中獲得正確的返回值

[英]Can't get the right return value from my API call

我正在使用http://ip-api.com/json API,並且試圖獲取一個可以容納一個人的城市和國家的對象。 這是我的代碼。

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;


var Person = {
    city: function() {
        $.getJSON(locationAPI, function(data) {
            return data.city;
        });
    },
    country: function() {
        $.getJSON(locationAPI, function(data) {
            return data.countryCode;
        });
    }
};

var x = Person.city;
console.log(x); });

這是輸出:

function () {
        $.getJSON(locationAPI, function(data) {
            return data.city;
        });
    }

我希望它為ex輸出一個值。 -Person.country =美國我在做什么錯?

您的問題是您認為.getJSON是一個簡單函數,但不是,它是一個promise函數,您有2種獲取數據的方法,或者在這樣的回調函數中:

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;
var Person;

$.getJSON(locationAPI, function(data) {
  Person = {
    city: data.city,
    country: data.country
  };

  var x = Person.city;
  console.log(x); });

});

或者您也可以做的是這樣的承諾:

var theCall = $.getJSON(locationAPI);

theCall.done(function(data) {...})

您可以使用.ajax()方法並設置async:false,這將使代碼等待ajax完成,然后再繼續(僅在設置變量后繼續)

但是,這不是這樣做的好方法,因為它阻止了瀏覽器等待調用,並且可能需要幾秒鍾才能完成!

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  success: function(data) {
    //stuff
    //...
  }
});

您可以從ajax的文檔中了解更多信息,或者從中了解更多信息是否可以將async:false設置為$ .getJSON調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM