我寫了一個小reddit圖像查看應用程序,並且如果用戶輸入一個有效的子reddit它工作正常。但我試圖處理一個不存在的reddit的情況下,無法弄清楚。當我使用.ajax和JSONP時,如何處理失敗的JSON請求?
function load_data(after) {
$.ajaxSetup({
"error": function() {
// this gets called every time, even for a valid sub-reddit
location.href = 'index.html';
}
});
fetchUrl = 'http://reddit.com/r/' + subreddit + '.json?jsonp=process_images&after=' + after;
$.ajax({
type: "GET",
url: fetchUrl,
dataType: "jsonp",
cycleTime: 1,
success: process_images
// error: handle_error <- this doesn't work, because we're using jsonp
// but if I take out jsonp, my whole app doesn't work any longer, since
// I'm trying to run it as a local .html file, and cross-site scripting
// security prevents it
});
}
load_data(after);
這是服務器的響應。但我不能用.ajax方法處理它:
GET http://www.reddit.com/r/%3Blk%3Blkl%3B.json?jsonp=process_images&after=&callback=jQuery1510605472848052159_1310668370375&_=1310668370433 404 (Not Found)
任何想法?
我試過這裏的一些建議,如jQuery.getJSON doesn't trigger callback - 但它每次都顯示基本相同的錯誤,其中'jQuery #####未被調用'的隨機數字。
這並不奏效。 :-( –
,這將不會與jsonp一起工作,因爲ccurrens提供的鏈接指出jsonp沒有提供錯誤處理,因此在ccurrens的答案中也提供了一些解決方法... – Rafay