修复 ajax 在直接执行 php 时返回成功和错误的解决方案



我有下面的ajax代码,它工作正常。如果我第一次发送请求,它工作正常。如果我第二次发送,它会返回成功和错误(各 1 个(。

$('#eproductForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: $('#eproductForm').attr('action'),
data: $('#eproductForm').serialize(),
cache: false,
async: false,
dataType: 'json',
success: function (response) {
$('#eproductModal').modal('hide');
$('#eproductForm')[0].reset();
save_success();
stockList();
},
error: function(response){
something_wrong();
}
});
return false;
});

你有解决方案吗?分享。谢谢

为什么最后返回 false!?我希望

save_success();
stockList();

这两个函数将带您到另一个地方,问题是当您返回 false 时,提交 aint 可能正常工作,因此它归结为错误。尝试在成功时返回 true/在错误中返回 false,也许这会解决它。如果这不起作用,请尝试让 Ajax 请求一个承诺,如

return new Promise ((resolve, reject) => {               
$.ajax({
type: 'post',
url: $('#eproductForm').attr('action'),
data: $('#eproductForm').serialize(),
cache: false,
async: false,
dataType: 'json',
success: function (response) {
resolve(response)
},
error: function(response){
reject(err)
}
}); 
}).then((response) => {                    
$('#eproductModal').modal('hide');
$('#eproductForm')[0].reset();
save_success();
stockList();}).catch((err) => {something_wrong();})

这将帮助您了解请求如何通过您的函数传递。此外,它还有助于在chrome开发人员工具中检查您的rquest并查看正在返回的状态,因此您可以推断出在什么点上正在中断