jQuery:处理内部服务器错误响应
我的页面上有一个表单,它通过 jQuery 将新数据添加到数据库中。它工作正常,但有时服务器会崩溃,我会收到500(内部服务器错误),但那是因为我的服务器很糟糕。
问题是,有时在 PHP 添加到数据库后,我会收到服务器错误,但我并没有收到成功消息,而是收到错误,即使添加已经完成。那么,如果出现错误,我应该如何处理才能确保 PHP 不会添加数据呢?
[是的,我最终会切换到新服务器,但没有服务器是完美的]
这是脚本:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#add").serialize(),
dataType: "json",
timeout: 8000,
beforeSend: function() {
var icon = '<p class="loading-add"></p>'; // loading icon
$('form#add').append(icon);
},
success: function(data) {
if (data.error == true) { // php returns error = true if name is invalid
alert('Invalid name.');
$('form#add').find('p').remove();
} else {
// make the addition
}
},
error: function () {
$('form#add').find('p').remove();
alert('Error. Try again.');
}
});
I have a form on a page that adds new data to a database via jQuery. It works fine, but sometimes the server craps out and I get a 500 (Internal Server Error), but that's because my server sucks.
The problem is that I sometimes get the server error after the PHP makes the addition to the database, but instead of getting a success message, I get the error, even though the addition has been made. So how should I go about this to make sure the PHP doesn't add the data if I get the error?
[And yes, I will eventually switch to a new server, but no server is perfect]
Here's the script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#add").serialize(),
dataType: "json",
timeout: 8000,
beforeSend: function() {
var icon = '<p class="loading-add"></p>'; // loading icon
$('form#add').append(icon);
},
success: function(data) {
if (data.error == true) { // php returns error = true if name is invalid
alert('Invalid name.');
$('form#add').find('p').remove();
} else {
// make the addition
}
},
error: function () {
$('form#add').find('p').remove();
alert('Error. Try again.');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 ajax 调用包装在一个函数中,并在出错时再次“请求”该函数。
与此相关的东西:
或者您可以有一个空闲函数,在出现错误时再次运行该函数之前,它会在几毫秒后再次检查:
上面使用的空闲函数:
但最好的事情是修复服务器..这个东西只是黑客和弥补另一个问题的补丁:坏服务器。 :)
所以这对于任何生产场景来说都不是一个好主意。
You could wrap you ajax call in a function and "reqest" the function again on error.
Something linke this:
Or you could have a idle function that checks again after some miliseconds before you do run the function again at the error:
Idle function used above:
But the best thing is to fix the server.. this stuff is just hacks and patches that compensate for another problem: the bad server. :)
So it's not a good idea for any production scenarios.
能否创建一个向数据库插入的控件,如果添加返回错误。
can you create a control of the insert to the database, if the addition of returned error.