2015-11-07 117 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