2015-11-07 74 views
0

我試圖弄清楚爲什麼我無法從ajax請求獲取變量值已經過了幾個小時。她是我的代碼:使用外部URL返回ajax變量

country_locator = function() { 
    var country_iso; 

    $.getJSON("https://api.wipmania.com/jsonp?callback=?", "", function(json) { 
     country_iso = json.address.country_code; 
    }); 

    return country_iso; 
} 

我也試過:

$.ajax({ 
     url: "https://api.wipmania.com/jsonp?callback=?", 
     async: false, 
     dataType: "json", 
     success: function(data) { 
      country_iso = data.address.country_code; 
     } 
    }); 

var country_iso; 
country_locator = function() { 
    $.getJSON("https://api.wipmania.com/jsonp?callback=?", "", function(json) { 
     country_iso = json.address.country_code; 
    }).success/complete(function() { 
     return country_iso; 
    }); 
} 

alert(country_locator());我得到了一個未定義的變量!這是非常令人沮喪:(

我發現這個鏈接:Get the variable of a json request outside the function (jquery)但沒能得到它的工作:/ 感謝您的時間和幫助 問候

回答

1

因爲$.getJSON是一個異步函數country_iso韓元「T填補,直到你的要求AJAX完整

我建議使用做到這一點使用deferred

var country_iso; 
country_locator = function() {  
    $.getJSON("https://api.wipmania.com/jsonp?callback=?", "", function(json) { 
     country_iso = json.address.country_code; 
    }); 
} 

country_locator().success(function() { 
    // do your logic here and use `country_iso` variable here. 
}); 

Read More About Deferred

Read More About getJSON

+0

感謝穆罕默德的非常快速的回覆,我一直對計算器社區:) 同樣的反應印象深刻,對不起,我忘了提,我也嘗試成功函數(編輯戰後初期),但仍然沒有積極的結果:(我現在試試你的解決方案,並回復給你 – Websphere

+0

umm,添加country_locator()。成功返回一個錯誤:未捕獲TypeError:無法讀取undefined屬性'success' – Websphere