2011-01-07 32 views
5

estoy desarrollando actualmente un tema de Tumblr y han construido un thingamabob jQuery JSON que utiliza la API Tumblr para hacer lo siguiente:¿Cómo mostrar un mensaje de error JSON?

El usuario haga clic en el enlace "tipo de mensaje" (por ejemplo, vídeo mensajes), en el cual stage jQuery usaría JSON para tomar todas las publicaciones relacionadas con ese tipo y luego mostrarlas dinámicamente en un área designada.

Ahora todo funciona perfectamente a todo color, excepto que con Tumblr siendo Tumblr y sus servidores recibiendo golpes de vez en cuando, el truco de la API de Tumblr a veces está fuera de línea. Ahora no puedo prever cuándo esta función estará inactiva, por lo que quiero mostrar un mensaje de error genérico si JSON (por alguna razón) no pudo cargar la publicación.

Verá que ya he escrito un código para mostrar un mensaje de error cuando jQuery no puede encontrar publicaciones relacionadas con ese tipo de publicación PERO no cubre ningún error del servidor. Nota: A veces me sale este error:

Error al cargar los recursos: 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 :)

Aquí está 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 cada vez Todo puede funcionar absolutamente bien para ti (o no), dependiendo del temperamento de Tumblr.


actualización bien, así que después de seguir jmorts responden por 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 usted gente jedi puede tomar otra mirada me 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."); 
      } 
     } 
    }); 
+0

Tenga en cuenta que JSON es la notación de objetos de JavaScript, no una forma de solicitar los datos. Puede cambiar su pregunta para hablar sobre AJAX en lugar de JSON, ya que JSON no es importante en esta pregunta. –

+0

Creo que has entendido mal qué es JSON. JSON es un formato de representación de datos; probablemente se esté refiriendo a XmlHttpRequest (comúnmente conocido como "AJAX" por alguna razón). –

+0

@Time Machine - Buen punto. JSON es solo un transporte de datos, como XML. Mientras que AJAX es una técnica para recuperar datos de un servidor sin volver a cargar la página, y puede devolver datos en XML, JSON, HTML, texto plano y otros formatos, a pesar de que la 'X' en AJAX significa 'XML' . – jmort253

Respuesta

6

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

Puede usar el objeto xhr para verificar el estado del objeto bruto XMLHttpRequest. Si 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, te recomiendo encarecidamente para la depuración de JavaScript: http://getfirebug.com/

ACTUALIZACIÓN:

La envoltura getJSON jQuery AJAX 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 solicitudes entre dominios usando esta función.

Si usted está confiando en JSONP usando mi respuesta original , entonces usted tendrá que poner en práctica 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/thread/73ca6be8071479fb

+0

Hola, jmort, gracias por la respuesta rápida, a riesgo de sonar ridículamente inexperto, tengo que decir que mi exposición a JSON y similares es extremadamente limitada. ¿Te importaría pedir un código porque nunca antes había trabajado con XMLHttpRequests? Diablos, incluso uno o dos enlaces solo para apuntarme en la dirección correcta sería genial :) - En una nota al margen, muchas gracias por tomarse el tiempo para analizar nuestra pregunta, definitivamente se agradece ... –

+0

En realidad, eres no muy lejos. Debería tomar todo el código en la función anónima después de esta línea y callback =? ', Y ponerlo en una función llamada "yourCallbackToRunIfSuccessful". Luego reemplace su devolución de llamada original con la mía, la que verifica xhr.status para ver cuál es el código de respuesta. Haré otra edición aclaratoria. – jmort253

+0

Háganos saber si esto funciona para usted. – jmort253

Cuestiones relacionadas