2011-01-07 86 views
5

我目前正在開發一個tumblr主題,建有一個使用的tumblr的API做以下jQuery的JSON thingamabob:如何顯示JSON錯誤信息?

的用戶會點擊「後輸入」鏈接(例如視頻的帖子),在該上stage jQuery將使用JSON來獲取與該類型相關的所有帖子,然後在指定區域動態顯示它們。

現在一切工作絕對桃色,除了與Tumblr是Tumblr和他們的服務器不時敲門,Tumblr API有時離線。現在我無法預見這個函數何時會失效,這就是爲什麼我想顯示一些通用的錯誤信息,如果JSON(無論什麼原因)無法加載帖子。

你會看到我已經寫了一些代碼來顯示錯誤消息時,jQuery無法找到任何帖子相關的帖子類型,但它不包括任何服務器錯誤。注:我有時會收到此錯誤:

無法加載資源:服務器與503狀態(服務暫時不可用)迴應

這是我需要編寫一些代碼,這503錯誤信息,但我稍微無知:)

這裏是jQuery的JSON代碼:

$('ul.right li').find('a').click(function() { 
    var postType = this.className; 
    var count = 0; 
    byCategory(postType); 
    return false; 

    function byCategory(postType, callback) { 
    $.getJSON('{URL}/api/read/json?type=' + postType + '&callback=?', function(data) { 
    var article = []; 
    $.each(data.posts, function(i, item) { 
    // i = index 
    // item = data for a particular post 
    switch(item.type) { 
    case 'photo': 
    article[i] = '<div class="post_wrap"><div class="photo" style="padding-bottom:5px;">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/XSTldh6ds/photo_icon.png" alt="type_icon"/></a>' 
     + '<a href="' + item.url + '" title="{Title}"><img src="' 
     + item['photo-url-500'] 
     + '"alt="image" /></a></div></div>'; 
    count = 1; 
    break; 
    case 'video': 
    article[i] = '<div class="post_wrap"><div class="video" style="padding-bottom:5px;">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon">' 
     + '<img src="http://static.tumblr.com/ewjv7ap/nuSldhclv/video_icon.png" alt="type_icon"/></a>' 
     + '<span style="margin: auto;">' 
     + item['video-player'] 
     + '</span>' 
     + '</div></div>'; 
    count = 1; 
    break; 
    case 'audio': 
    if (use_IE == true) { 
    article[i] = '<div class="post_wrap"><div class="regular">' 
      + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/R50ldh5uj/audio_icon.png" alt="type_icon"/></a>' 
     + '<h3><a href="' 
     + item.url 
     + '">' 
     + item['id3-artist'] 
     +' - ' 
     + item['id3-title'] 
     + '</a></h3>' 
     + '</div></div>'; 

    } else { 
    article[i] = '<div class="post_wrap"><div class="regular">' 
      + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/R50ldh5uj/audio_icon.png" alt="type_icon"/></a>' 
     + '<h3><a href="' 
     + item.url 
     + '">' 
     + item['id3-artist'] 
     +' - ' 
     + item['id3-title'] 
     + '</a></h3><div class="player">' 
     + item['audio-player'] 
     + '</div>' 
     + '</div></div>'; 
    }; 
    count = 1; 
    break; 
    case 'regular': 
    article[i] = '<div class="post_wrap"><div class="regular">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/dwxldhck1/regular_icon.png" alt="type_icon"/></a><h3><a href="' 
     + item.url 
     + '">' 
     + item['regular-title'] 
     + '</a></h3><div class="description_container">' 
     + item['regular-body'] 
     + '</div></div></div>'; 
    count = 1; 
    break; 
    case 'quote': 
    article[i] = '<div class="post_wrap"><div class="quote">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/loEldhcpr/quote_icon.png" alt="type_icon"/></a><blockquote><h3><a href="' + item.url + '" title="{Title}">' 
     + item['quote-text'] 
     + '</a></h3></blockquote><cite>- ' 
     + item['quote-source'] 
     + '</cite></div></div>'; 
    count = 1; 
    break; 
    case 'conversation': 
    article[i] = '<div class="post_wrap"><div class="chat">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/MVuldhcth/conversation_icon.png" alt="type_icon"/></a><h3><a href="' 
     + item.url 
     + '">' 
     + item['conversation-title'] 
     + '</a></h3></div></div>'; 
    count = 1; 
    break; 
    case 'link': 
    article[i] = '<div class="post_wrap"><div class="link">' 
     + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/EQGldhc30/link_icon.png" alt="type_icon"/></a><h3><a href="' 
     + item['link-url'] 
     + '" target="_blank">' 
     + item['link-text'] 
     + '</a></h3></div></div>'; 
    count = 1; 
    break; 
    default: 
    alert('No Entries Found.'); 
    }; 
    }) // end each 

    if (!(count == 0)) { 
    $('#content_right') 
     .hide('fast') 
     .html('<div class="first_div"><span class="left_corner"></span><span class="right_corner"></span><h2>Displaying ' 
     + postType 
     + ' Posts Only</h2></div>' 
     + article.join('')) 
    .slideDown('fast') 
    } else { 
    $('#content_right') 
    .hide('fast') 
    .html('<div class="first_div"><span class="left_corner"></span><span class="right_corner"></span><h2>Hmmm, currently there are no ' 
     + postType 
     + ' posts to display</h2></div>') 
    .slideDown('fast') 
    } 


    // end getJSON 
    }); // end byCategory 
    } 
}); 

如果您想在行動中看到演示,看看Elegantem但千萬注意,永遠事情可能對你(或不)來說絕對好,這取決於Tumblr的氣質。


更新好了,打完之後jmorts回答下面接近信爲凌晨2點允許的話,我已經生產了沒有成功將下面的代碼 - 有沒有警報彈出。 Myabe我是一個布偶,也許我只是scheleeeepy但如果你的絕地人可以採取另一種偷看我會很感激:)

$('ul.right li').find('a').click(function() { 
     var postType = this.className; 
     var count = 0; 
     byCategory(postType); 
     return false; 

     function byCategory(postType, callback) { 
      $.getJSON('{URL}/api/read/json?type=' + postType + '&callback=?', function(data, textStatus, xhr) { // main callback function 
      if(xhr.status == 500 || xhr.status == 404 || xhr.status == 503) { 
        yourErrorHandler(data, textStatus, xhr); // success 
       } else { 
        yourCallbackToRunIfSuccessful(data); // failed 
       } 
       } 
     ); 


     function yourCallbackToRunIfSuccessful(data) { 
      var article = []; 
       $.each(data.posts, function(i, item) { 
       // i = index 
       // item = data for a particular post 
       switch(item.type) { 
       case 'photo': 
       article[i] = '<div class="post_wrap"><div class="photo" style="padding-bottom:5px;">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/XSTldh6ds/photo_icon.png" alt="type_icon"/></a>' 
          + '<a href="' + item.url + '" title="{Title}"><img src="' 
          + item['photo-url-500'] 
          + '"alt="image" /></a></div></div>'; 
       count = 1; 
       break; 
       case 'video': 
       article[i] = '<div class="post_wrap"><div class="video" style="padding-bottom:5px;">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon">' 
          + '<img src="http://static.tumblr.com/ewjv7ap/nuSldhclv/video_icon.png" alt="type_icon"/></a>' 
          + '<span style="margin: auto;">' 
          + item['video-player'] 
          + '</span>' 
          + '</div></div>'; 
       count = 1; 
       break; 
       case 'audio': 
       if (use_IE == true) { 
       article[i] = '<div class="post_wrap"><div class="regular">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/R50ldh5uj/audio_icon.png" alt="type_icon"/></a>' 
          + '<h3><a href="' 
          + item.url 
          + '">' 
          + item['id3-artist'] 
          +' - ' 
          + item['id3-title'] 
          + '</a></h3>' 
          + '</div></div>'; 

       } else { 
       article[i] = '<div class="post_wrap"><div class="regular">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/R50ldh5uj/audio_icon.png" alt="type_icon"/></a>' 
          + '<h3><a href="' 
          + item.url 
          + '">' 
          + item['id3-artist'] 
          +' - ' 
          + item['id3-title'] 
          + '</a></h3><div class="player">' 
          + item['audio-player'] 
          + '</div>' 
          + '</div></div>'; 
       }; 
       count = 1; 
       break; 
       case 'regular': 
       article[i] = '<div class="post_wrap"><div class="regular">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/dwxldhck1/regular_icon.png" alt="type_icon"/></a><h3><a href="' 
          + item.url 
          + '">' 
          + item['regular-title'] 
          + '</a></h3><div class="description_container">' 
          + item['regular-body'] 
          + '</div></div></div>'; 
       count = 1; 
       break; 
       case 'quote': 
       article[i] = '<div class="post_wrap"><div class="quote">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/loEldhcpr/quote_icon.png" alt="type_icon"/></a><blockquote><h3><a href="' + item.url + '" title="{Title}">' 
          + item['quote-text'] 
          + '</a></h3></blockquote><cite>- ' 
          + item['quote-source'] 
          + '</cite></div></div>'; 
       count = 1; 
       break; 
       case 'conversation': 
       article[i] = '<div class="post_wrap"><div class="chat">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/MVuldhcth/conversation_icon.png" alt="type_icon"/></a><h3><a href="' 
          + item.url 
          + '">' 
          + item['conversation-title'] 
          + '</a></h3></div></div>'; 
       count = 1; 
       break; 
       case 'link': 
       article[i] = '<div class="post_wrap"><div class="link">' 
          + '<a href="' + item.url + '" title="{Title}" class="type_icon"><img src="http://static.tumblr.com/ewjv7ap/EQGldhc30/link_icon.png" alt="type_icon"/></a><h3><a href="' 
          + item['link-url'] 
          + '" target="_blank">' 
          + item['link-text'] 
          + '</a></h3></div></div>'; 
       count = 1; 
       break; 
       default: 
       alert('No Entries Found.'); 
       }; 
       }) // end each 

       if (!(count == 0)) { 
       $('#content_right') 
       .hide('fast') 
       .html('<div class="first_div"><span class="left_corner"></span><span class="right_corner"></span><h2>Displaying ' 
        + postType 
        + ' Posts Only</h2></div>' 
        + article.join('')) 
       .slideDown('fast') 
       } else { 
        $('#content_right') 
        .hide('fast') 
        .html('<div class="first_div"><span class="left_corner"></span><span class="right_corner"></span><h2>Hmmm, currently there are no ' 
         + postType 
         + ' posts to display</h2></div>') 
        .slideDown('fast') 
       } 


       // end getJSON 
      }; // end byCategory 

      function yourErrorHandler(data,textStatus,xhr) { 
       alert("Server returned status code " + xhr.status + ". Try again later."); 
      } 
     } 
    }); 
+0

注意,JSON是JavaScript對象符號,而不是請求數據的方式。你可以改變你的問題來談論AJAX而不是JSON,因爲JSON在這個問題上並不重要。 – 2011-01-07 01:47:18

+0

我認爲你誤解了JSON是什麼。 JSON是一種數據表示格式;你可能指的是XmlHttpRequest(出於某種原因俗稱「AJAX」)。 – 2011-01-07 01:54:15

+0

@時間機器 - 好點。 JSON只是一種數據傳輸,就像XML一樣。儘管AJAX是一種用於從服務器檢索數據而不重新加載頁面的技術,並且可以以XML,JSON,HTML,純文本和其他格式返回數據,儘管AJAX中的'X'代表'XML' 。 – jmort253 2011-01-07 01:55:30

回答

6

你的回調,其實需要你不顯示2個其他參數:

 $.getJSON('{URL}/api/read/json?type=' + postType + 
      '&callback=?', 
       function(data, textStatus, xhr) { // main callback function 
       if(xhr.status == 500 || xhr.status == 404 || xhr.status == 503) { 
        yourErrorHandler(data, textStatus, xhr); // success 
       } else { 
        yourCallbackToRunIfSuccessful(data); // failed 
       } 
       } 
     ); 

     // your original code, but wrapped up in it's own function definition 
     function yourCallbackToRunIfSuccessful(data) { 
     var article = []; 
     $.each(data.posts, function(i, item) { 
     // i = index 
     // item = data for a particular post 
     switch(item.type) { 
      case 'photo': 
      ... 
      ... 
     } 

     function yourErrorHandler(data,textStatus,xhr) { 
      alert("Server returned status code " + xhr.status + ". Try again later."); 
     } 

您可以使用xhr對象來檢查原始XMLHttpRequest對象的狀態。如果你得到404,503,500等,那麼你可以顯示你的錯誤信息或運行你的備用功能。

http://api.jquery.com/jQuery.ajax

另外,如果您還沒有Firefox的Firebug,我強烈推薦它的JavaScript調試:http://getfirebug.com/

UPDATE:

的的JQuery的getJSON AJAX包裝沒有錯誤回調處理程序。相反,你需要使用常規的JQuery AJAX的處理程序,讓您的JSON請求:

jQuery.ajax({ 
    type: "GET", 
    url: '{URL}/api/read/json?type=' + postType + 
      '&callback=?', 
    dataType: "json", 
    success: function(results){ 
     console.info("Success!"); 
     yourCallbackToRunIfSuccessful(results); 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 
     alert("Error"); 
     yourErrorHandler(XMLHttpRequest, textStatus, errorThrown); 
    } 
    }); 

重要的是要注意,這不是JSONP是非常重要的。這意味着您無法使用此功能進行跨域請求。

如果您在使用我的原來的答覆依靠JSONP,那麼你,讓你設置一個的setInterval事件輪詢將在你的回調而改變的值需要實現的解決方案。更多詳細信息可以在這裏找到:

http://groups.google.com/group/jquery-dev/browse_thread/thread/73ca6be8071479fb

+0

嗨jmort,感謝您的快速回復 - 風險聽起來可笑的經驗不足我不得不說,我對JSON和類似的暴露極其有限。你介意我是否因爲以前從未使用XMLHttpRequests而請求過一些代碼?甚至只是一個或兩個鏈接只是爲了指向我在正確的方向將是真棒:) - 在旁註中,非常感謝您花時間來考慮我們的問題,這絕對是讚賞... – 2011-01-07 01:42:57

+0

其實,你不遠處。在這行&callback =?'之後,你應該把匿名函數中的所有代碼放到一個名爲「yourCallbackToRunIfSuccessful」的函數中。然後將我的原始回調替換爲我的回調函數,它檢查xhr.status以查看響應代碼是什麼。我會再做一個澄清的編輯。 – jmort253 2011-01-07 01:47:25

+0

請讓我們知道這是否適合您。 – jmort253 2011-01-07 02:01:33