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