jQuery ajax(jsonp)忽略超時并且不會觸發(fā)錯誤事件為了添加一些基本的錯誤處理,我想重寫一段使用jQuery的$ .getJSON來從Flickr中提取一些照片的代碼。這樣做的原因是$ .getJSON不提供錯誤處理或使用超時。因為$ .getJSON只是$ .ajax的包裝,所以我決定改寫這個東西并驚喜,它完美無缺?,F(xiàn)在開始有趣了。當(dāng)我故意導(dǎo)致404(通過更改URL)或?qū)е戮W(wǎng)絡(luò)超時(沒有連接到互聯(lián)網(wǎng))時,錯誤事件根本不會觸發(fā)。我不知道自己做錯了什么。非常感謝幫助。這是代碼:$(document).ready(function(){
// var jsonFeed = "http://api.flickr.com/services/feeds/photos_public.gne"; // correct URL
var jsonFeed = "http://api.flickr.com/services/feeds/photos_public.gne_______"; // this should throw a 404
$.ajax({
url: jsonFeed,
data: { "lang" : "en-us",
"format" : "json",
"tags" : "sunset"
},
dataType: "jsonp",
jsonp: "jsoncallback",
timeout: 5000,
success: function(data, status){
$.each(data.items, function(i,item){
$("<img>").attr("src", (item.media.m).replace("_m.","_s."))
.attr("alt", item.title)
.appendTo("ul#flickr")
.wrap("<li><a href=\"" + item.link + "\"></a></li>");
if (i == 9) return false;
});
},
error: function(XHR, textStatus, errorThrown){
alert("ERREUR: " + textStatus);
alert("ERREUR: " + errorThrown);
}
});});我想補(bǔ)充說,當(dāng)jQuery版本為1.4.2時,會問這個問題
3 回答

慕標(biāo)琳琳
TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
jQuery 1.5及更高版本可以更好地支持JSONP請求的錯誤處理。但是,您需要使用該$.ajax
方法而不是$.getJSON
。對我來說,這有效:
var?req?=?$.ajax({ ????url?:?url, ????dataType?:?"jsonp", ????timeout?:?10000});req.success(function()?{ ????console.log('Yes!?Success!');});req.error(function()?{ ????console.log('Oh?noes!');});
超時似乎可以解決問題并在10秒后沒有成功請求時調(diào)用錯誤處理程序。

寶慕林4294392
TA貢獻(xiàn)2021條經(jīng)驗 獲得超8個贊
一個解決方案,如果你堅持使用jQuery 1.4:
var timeout = 10000;var id = setTimeout( errorCallback, timeout );$.ajax({ dataType: 'jsonp', success: function() { clearTimeout(id); ... }});
- 3 回答
- 0 關(guān)注
- 628 瀏覽
添加回答
舉報
0/150
提交
取消