我有这个ajax代码来处理php文件
$.ajax({
url:'vals/Package.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
swal("Success", "We will contact you soon! Thank you :)", "success");
},
error:function(data){
swal("Sorry", "Failed to send order. Please try later :(", "error");
}
});
在我的Package.php
中$Query = mysqli_query($connecDB,"insert into query here");
if($Query){
echo 'success message';
}
else{
echo 'error here';
}
如果插入数据库时出错,我该如何将其发送到sweetalert?
如果我删除if else条件,则显示Success消息。我也试图显示错误消息。
答案 0 :(得分:1)
您现在只是回显一个错误字符串,但该响应仍然会以状态200标头发送。您需要做的是明确设置标题:
header('HTTP/1.1 500 Internal Server Error');
echo 'error message';
我认为我说jQuery只是将所有非HTTP 200响应视为错误(即不成功的请求)。可能存在一些例外情况,例如404,301或201状态代码。无论哪种方式,如果您想表明一个严重的问题:使用http 500(内部服务器错误)
答案 1 :(得分:1)
最佳解决方案是使用try/catch并发送两种消息作为响应,以下是使用您自己的代码剪切:
在你的package.php中
try {
$Query = mysqli_query($connecDB, "insert into query here");
if ($Query) {
echo 'success message';
} else {
throw new Exception('dummy error message');
}
} catch (Exception $exc) {
//handle any errors in your code, including connection issues
echo 'error'; //this will be your "flag" to handle on the client side
//and if you want, can also log the error with
//$exc->getMessage() or $exc->getTraceAsString()
die;
}
在JS文件中:
$.ajax({
url: 'vals/Package.php',
data: $(this).serialize(),
type: 'POST',
success: function (data) {
if (data !== 'error') {
swal("Success", "We will contact you soon! Thank you :)", "success");
} else {
//our handled error
swal("Sorry", "Failed to send order. Please try later :(", "error");
}
},
error: function (data) {
//other errors that we didn't handle
swal("Sorry", "Failed to send order. Please try later :(", "error");
}
});
使用try/catch您的代码将防止出现意外错误。 注意:当然,您可以编辑标题而不是回显您自己的标志,并返回将在您的ajax错误函数中处理的http错误。
答案 2 :(得分:1)
我找到了这段代码,似乎正常工作
if($Query){
}
else{
header('HTTP/1.1 500 Internal Server...');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}