Se il server invia un codice di stato diverso rispetto a 200, viene eseguita la richiamata di errore:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
e di registrare un gestore errori globale è possibile utilizzare il metodo $.ajaxSetup()
:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
altro il modo è usare JSON. Così si potrebbe scrivere un filtro di un'azione personalizzata sul server che cattura eccezione e li trasforma in JSON risposta:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
e poi decorare la vostra azione di controllo con questo attributo:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
e, infine, invocarlo:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
fonte
2011-01-16 20:12:59
Vedere [post di beckelmans] (http://beckelman.net/post/2010/03/18/Handling-Errors-During-Ajax-Calls-With-ASPNET-MVC.aspx) per un buon esempio. La risposta di Darin a questo post è buona, ma non impostare il codice di stato corretto per un errore. – Dan
Purtroppo il link è ora rotto –
Ecco il link sulla macchina del wayback: https://web.archive.org/web/20111011105139/http://beckelman.net/post/2010/03/18/Handling-Errors- Durante-Ajax-Calls-With-ASPNET-MVC.aspx – BruceHill