如果API数据无法加载,则执行某些操作

时间:2014-02-26 20:14:09

标签: javascript jquery json api geolocation

我正在使用名为wipmania的地理查找API来查找用户所在的国家/地区并执行一些不同类型的事情。

jQuery.getJSON('https://api.wipmania.com/jsonp?callback=?', function (data) { 
 // Do my code based on result here. 
});

我刚发现这个API现在失败了,所以我的网站没有执行代码,我需要某种退回。

我不确定,因为如果有文件说明如何在2秒后没有返回数据然后做其他事情,我无法访问他们的网站。

有没有人知道我可以退回API而不返回任何内容的方式。它基本上只是等待它永远返回。用Puesdo语言猜猜是否正在寻找像

这样的东西
if API call returns data {
 // execute code per country
} else {
 // do other code as fallback we can't detect country
}

1 个答案:

答案 0 :(得分:2)

您可以使用fail()回调来处理jQuery.getJSON()的不成功结果。例如:

jQuery.getJSON( "example.json", function() {
    console.log( "success" );
})
.fail(function() {
    console.log( "Failed to get JSON" );
});