2011-07-14 39 views
1

我寫了一個小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 #####未被調用'的隨機數字。

回答

2

實際上,這是跨域腳本注入的一個限制,這是jQuery用於JSONP的一個限制。

jquery-jsonp plugin和較新版本的jQuery都通過實現超時來解決這個問題。他們仍然無法捕捉錯誤。

如果可能,更好的解決方案是使用CORS (Cross-Origin Resource Sharing)

新版本的jQuery支持CORS,但瀏覽器和遠程站點也必須支持它。

當前版本的所有主流桌面瀏覽器僅支持CORS,僅限於版本10的Internet Explorer。

0
$.ajax({ 
    statusCode: { 
    404: function() { 
     //handle the 404 here 
     alert('page not found'); 
    } 
    } 
}); 

這裏是裁判:http://api.jquery.com/jQuery.ajax/

編輯

與JSONP一看便知上述由ccurrens

+0

這並不奏效。 :-( –

+1

,這將不會與jsonp一起工作,因爲ccurrens提供的鏈接指出jsonp沒有提供錯誤處理,因此在ccurrens的答案中也提供了一些解決方法... – Rafay

1

您可以在服務器響應添加一些標題,可讓跨域不會工作如果你想...

+0

您是否有鏈接到示例? –

+0

https://developer.mozilla.org/en/HTTP_access_control – ChristopheCVB

+0

這叫做CORS,但它只在遠程站點支持它時才起作用,例如YQL支持它,但Stack Exchange API不支持。 – hippietrail

4

看看this answer到另一個題。

本質上它是JQuery中jsonp實現的限制。流行的答案是使用this js插件。