将我重定向到 jQuery .ajax() 错误的默认错误页面:
我写了一个小型的 ruby Sinatra 应用程序。有时会抛出错误(例如数据库连接不存在)。但是,默认索引页始终有效(无需数据库连接)。
我使用 jQuery 来处理触发数据创建的请求。但是当后端发生错误时,我想显示默认的错误页面。这不起作用,因为 jQuery 创建请求并忽略错误(因此当数据库不可用时什么也不会发生)。我的代码看起来像这样:
$(document).ready(function() {
$("form").bind("submit", function(event) {
event.preventDefault();
$.ajax({
type:"POST",
url:"/new",
data:$("#form").serialize(),
dataType:"json",
success:function(data){
// handling of input data
},
error:function(xhr, ajaxOptions, thrownError){
// show default error page
}
});
});
});
我设法通过这样做实现了我想要的目标:
error:function(xhr, ajaxOptions, thrownError){
alert something;
}
但我想这只是因为语法错误而起作用(正确的语法是alert("something");)
是否有正确的方法来重定向到默认错误页面?
I've written a little ruby Sinatra app. From time to time an error is thrown (e.g. database connection is not there). However the default index page always works (no database connection necessary).
I've used jQuery to handle the request that triggers the creation of data. But when a backend error occurs, I'd like to show the default error page. This is not working because jQuery creates the request and just ignores the error (so nothing happens when the database is not available). My code looks something like this:
$(document).ready(function() {
$("form").bind("submit", function(event) {
event.preventDefault();
$.ajax({
type:"POST",
url:"/new",
data:$("#form").serialize(),
dataType:"json",
success:function(data){
// handling of input data
},
error:function(xhr, ajaxOptions, thrownError){
// show default error page
}
});
});
});
I managed to achieve what I wanted by doing this:
error:function(xhr, ajaxOptions, thrownError){
alert something;
}
But I suppose this just works because of the syntax error (The correct syntax would be alert("something");)
Is there a proper way to redirect to the default error page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看默认的 ajax 设置,这样您就不必为发出的每个 Ajax 请求执行此操作。 http://api.jquery.com/jQuery.ajaxSetup/
如果您有 ajax 请求并且您的数据库不可用,不会出现 Ajax 错误,因为页面仍然可以调用。也许您必须检查成功页面上的响应是否包含“ERROR”或其他内容?或者将标头代码更改为 200 以外的其他代码,以便调用 Ajax 请求的错误。
Look at the default ajax settings, so you don´t have to do this for each Ajax request you make. http://api.jquery.com/jQuery.ajaxSetup/
If you have an ajax request and your Database is not available, there is not Ajax error because the page can still be called. Maybe you have to check the response on the success page if it contains "ERROR" or something? Or change the header code to a different one then 200 so the error of the Ajax request will be called.
试试这个:
Try this: