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.
用户点击“post type”链接(如视频贴子),在此阶段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 API有时候会离线。现在我无法预见这个函数何时会停止,这就是为什么如果JSON(无论出于什么原因)无法加载post,我想要显示一些通用的错误消息。
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找不到与该post类型相关的任何文章时显示一条错误消息,但它不包含任何服务器错误。注意:我有时会得到这个错误:
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 Elegantem but do note that everything might work absolutely fine for you (or not), depending on Tumblr's temperament.
如果你想看看这个演示的实际效果,可以看看Elegantem,但要注意的是,根据Tumblr的脾气,每样东西都可能完全适合你(或不适合)。
Update Okay, so after following jmorts answer underneath as close to the letter as 2am allows, I've churned out the following code without success - there's no alert popping up. Myabe I'm a muppet, maybe I'm just scheleeeepy but if you jedi folks can take another peek I'd really appreciate it :)
$('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 个解决方案
#1
6
Your callback actually takes 2 other parameters you're not showing:
你的回调实际上取了两个你没有显示的参数:
$.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
#1
6
Your callback actually takes 2 other parameters you're not showing:
你的回调实际上取了两个你没有显示的参数:
$.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