Pregunta

Actualmente estoy desarrollando un tema de Tumblr y he construido un jQuery JSON thingamabob que utiliza la API Tumblr para hacer lo siguiente:

El usuario haga clic en el enlace "tipo de mensaje" (por ejemplo, vídeo mensajes), en el que la etapa de jQuery usaría JSON para agarrar todos los mensajes que está relacionado con ese tipo y luego dinámicamente mostrarlos en un área designada.

Ahora todo funciona absolutamente color de rosa, con la excepción de que Tumblr Tumblr y ser sus servidores teniendo un knock vez en cuando, la API Tumblr cosita es a veces fuera de línea. Ahora bien, no podemos prever cuando esta función no estará disponible, que es por eso que quiero mostrar algún mensaje de error genérico si JSON (por cualquier razón) no ha podido cargar el cargo.

Usted verá ya he escrito algo de código para mostrar un mensaje de error cuando jQuery no puede encontrar entradas relacionadas con este tipo de post pero no cubrir cualquier error de servidor. Nota: a veces me sale este error:

Error al recurso de carga: el servidor responde con un estado de 503 (Servicio no disponible temporalmente)

Es por este mensaje de error 503 que tengo que escribir algo de código, pero estoy un poco desorientado:)

Este es el código 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
  }
 });

Si desea ver la demo en acción, echa un vistazo a Elegantem pero tenga en cuenta que todo puede trabajo absolutamente bien para usted (o no), dependiendo del temperamento de Tumblr.


Actualizar Está bien, así que después de responder a las siguientes jmorts debajo de lo más cercano a la carta como 02 a.m. permite, he produjo el siguiente código sin éxito - no hay alerta apareciendo. MYABE Soy un Muppet, tal vez estoy scheleeeepy pero si jedi gente puede tener otra mirada lo agradecería mucho:)

$('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.");
            }
        }
    });
¿Fue útil?

Solución

A su función realmente tiene otros 2 parámetros que no está mostrando:

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

Se puede utilizar el objeto XHR para comprobar el estado del objeto XMLHttpRequest prima. Si se obtiene un 404, 503, 500, etc, entonces puede mostrar su mensaje de error o ejecutar su función alternativa.

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

Además, si usted no tiene ya Firebug para Firefox, lo recomiendo encarecidamente para la depuración de JavaScript: http: // getfirebug.com/

ACTUALIZACIÓN:

El getJSON jQuery AJAX envoltorio no tiene un controlador de devolución de llamada de error. En su lugar, tendrá que utilizar el controlador regular de jQuery AJAX para realizar su solicitud 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);
     }
  });

Es importante tener en cuenta que esto no es JSONP. Esto significa que no puede hacer peticiones entre dominios utilizando esta función.

Si usted está confiando en JSONP usando mi respuesta original , a continuación, tendrá que implementar una solución en la que se establece un evento setInterval para sondear un valor que se va a cambiar en su devolución de llamada. Más detalles se pueden encontrar aquí:

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top