javascript 如何显示 JSON 错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4621747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:20:06  来源:igfitidea点击:

How to display a JSON error message?

javascriptjqueryjsontumblrhttp-status-code-503

提问by Tiny Giant Studios

I'm currently developing a tumblr theme and have built a jQuery JSON thingamabob that uses the Tumblr API to do the following:

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

The user would click on the "post type" link (e.g. Video Posts), at which stage jQuery would use JSON to grab all the posts that's related to that type and then dynamically display them in a designated area.

用户将单击“帖子类型”链接(例如视频帖子),在此阶段 jQuery 将使用 JSON 获取与该类型相关的所有帖子,然后在指定区域动态显示它们。

Now everything works absolutely peachy, except that with Tumblr being Tumblr and their servers taking a knock every now and then, the Tumblr API thingy is sometimes offline. Now I can't foresee when this function will be down, which is why I want to display some generic error message if JSON (for whatever reason) was unable to load the post.

现在一切正常,除了 Tumblr 是 Tumblr 并且他们的服务器时不时地敲门,Tumblr API 有时会离线。现在我无法预见此功能何时会关闭,这就是为什么我想在 JSON(无论出于何种原因)无法加载帖子时显示一些通用错误消息的原因。

You'll see I've already written some code to show an error message when jQuery can't find any posts related to that post type BUT it doesn't cover any server errors. Note: I sometimes get this error:

您会看到我已经编写了一些代码来在 jQuery 找不到与该帖子类型相关的任何帖子时显示错误消息,但它不包括任何服务器错误。注意:我有时会收到此错误:

Failed to load resource: the server responded with a status of 503 (Service Temporarily Unavailable)

加载资源失败:服务器响应状态为 503(服务暂时不可用)

It is for this 503 Error message that I need to write some code, but I'm slightly clueless :)

正是针对这个 503 错误消息,我需要编写一些代码,但我有点无能为力:)

Here's the jQuery JSON code:

这是 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
  }
 });

If you'd like to see the demo in action, check out Elegantembut do note that everything might work absolutely fine for you (or not), depending on Tumblr's temperament.

如果您想查看实际演示,请查看Elegantem,但请注意,根据 Tumblr 的气质,一切可能对您来说都非常适用(或不适用)。



Update更新好的,所以在凌晨 2 点允许的尽可能接近信件的下方跟随 jmorts 回答之后,我制作了以下代码但没有成功 - 没有弹出警报。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.");
            }
        }
    });

回答by jmort253

Your callback actually takes 2 other parameters you're not showing:

您的回调实际上采用了您未显示的其他 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.");
       }

You can use the xhr object to check the status of the raw XMLHttpRequest object. If you get a 404, 503, 500, etc then you can display your error message or run your alternate function.

您可以使用 xhr 对象来检查原始 XMLHttpRequest 对象的状态。如果您收到 404、503、500 等信息,则可以显示错误消息或运行备用功能。

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

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

Also, if you don't already have Firebug for Firefox, I'd highly recommend it for JavaScript debugging: http://getfirebug.com/

另外,如果您还没有用于 Firefox 的 Firebug,我强烈推荐它用于 JavaScript 调试:http: //getfirebug.com/

UPDATE:

更新:

The getJSON JQuery AJAX wrapper does not have an error callback handler. Instead, you'll need to use the regular JQuery AJAX handler to make your JSON request:

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);
     }
  });

It's important to note that this is NOT JSONP. This means you cannot make cross-domain requests using this function.

需要注意的是,这不是 JSONP。这意味着您不能使用此功能进行跨域请求。

If you're relying on JSONP using my original answer, then you'll need to implement a solution whereby you set a setInterval event to poll a value that will be changed in your callback. More details can be found here:

如果您使用我的原始答案依赖 JSONP ,那么您需要实施一个解决方案,通过该解决方案设置 setInterval 事件来轮询将在您的回调中更改的值。更多详情可在这找到:

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

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