detecting returned errors with $.post
I'm using $.post to send a query to a JSP which returns some awesome data for me.
If the query is malformed, however, the page returns with "error on page" and an HTTP Status of 500 Internal Server Error
in jQuery, how can I detect this error so I can tell the user of the failure?
runQuery : function () {
$.post(
admin_stats.runQueryURL,
{
buster : Math.random,
statsQuery: admin_stats.getQuery(),
jsp: 'admin_s开发者_Python百科tatsQuery'
},
admin_stats.handleStatsQuery,
"html"
);
the returned data is an HTML table which is sufficient for this project at the moment.
Also: totally open to criticism if this is ugly or not the way I should be doing things =)
You need to use the $.ajax
method instead:
$.ajax({
type: 'POST',
url: admin_stats.runQueryURL,
data: {
buster : Math.random,
statsQuery: admin_stats.getQuery(),
jsp: 'admin_statsQuery'
},
success: admin_stats.handleStatsQuery,
error: admin_stats.error, //change this to your handler
dataType: "html"
});
See here for more info: http://api.jquery.com/jQuery.ajax/
Take a look at .ajaxError
. From the documentation:
Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
Documented example:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});
If you want to give a message specific to the type of error returned, you can do so like this:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if(xhr.status == 500) {
$(this).text('internal server error');
} else if (xhr.status == 404) {
$(this).text('page not found');
}
// etc.
});
精彩评论