如何显示JSON错误消息?

时间:2011-01-07 01:30:51

标签: javascript jquery json tumblr http-status-code-503

我目前正在开发一个tumblr主题,并构建了一个使用Tumblr API执行以下操作的jQuery JSON thingamabob:

用户可以点击“帖子类型”链接(例如视频帖子),在这个阶段,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回答下面接近2am允许的字母后,我已经生成了以下代码而没有成功 - 没有弹出警报。 Myabe我是一个布偶,也许我只是狡猾,但如果你们绝地人可以再看一眼,我真的很感激它:)

$('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.");
            }
        }
    });

1 个答案:

答案 0 :(得分:6)

您的回调实际上需要另外两个您未显示的参数:

     $.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

此外,如果您还没有Firebug for Firefox,我强烈建议您进行JavaScript调试:http://getfirebug.com/

<强>更新

getJSON JQuery 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