捕获 Ajax 查询 POST 错误不起作用



我写了一些代码,使用JQuery和PHP将数据输入到我的sql数据库中,它工作了。但是,我需要在数据库服务器脱机、sql抛出错误或应该出现错误时执行Ajax请求的错误块。

问题是,ajax请求的错误块永远不会被执行。永远只是成功的障碍。 sql查询错误或数据库服务器离线

我已经尝试过失败块和jQuery.$.get(),但这也不起作用。但是我更喜欢ajax请求。

到目前为止,我写了以下代码:
//JavaScript-function to insert data into a database. The parameter is an SQL-INSERT statement.
function insertIntoDatabase(sqlQuery)
{
var result;
$.ajax({
type: "POST",
url: "../../general/clientHelper.php",
data: {sql: sqlQuery},
async: false,
error: function()
{
if(sqlQuery.split(" ")[0] != "INSERT") console.log("SQL-Query is not an INSERT statement");
result = false;
},
success: function()
{
result = true;
}
});

return result;
}
<?php
//clientHelper.php - Insert data into the database.
if(isset($_POST['sql'])) insertIntoDatabase($_POST['sql']);
function insertIntoDatabase($sqlQuery)
{
$ip = "10.10.10.1";
$port = 3306;
$username = "candidate";
$password = "candidate";
$dbname = "cqtsdb";
$connection = new mysqli($ip, $username, $password, $dbname, $port);
$connection->query($sqlQuery);
$connection->close();

exit();
}
?>

我现在不知道该怎么办:/请帮忙<3

UPDATE:

我发现,如果我向成功函数添加一个参数,如果发生错误,它会被错误的文本填充。如果一切都是正确的,那么文本就是"所以我不需要做任何其他的检查:)

success: function(data)
{
if(data == "") result = true; 
else  result = false;
}

检查查询结果,如果成功,则向ajax返回某个值,如1,如果不成功,则返回0。然后在ajax成功函数中检查该值并相应地显示消息或任何您想要做的事情。

我使用过程式PHP,我这样做

function leave($msg, $conn, $type){
//$msg is the message I want to display to the user.
//$type is the query result type I explained above.
//$conn is to close the connection.
echo json_encode(array(
"msg" => $msg,
"type" => $type
));
mysqli_close($conn);
exit();
}

以这种方式调用这个函数

$result = mysqli_query($conn, $query);
if ($result) {
leave('done', $conn, 1);
} else {
leave('something went wrong', $conn, 0);
}

检查如下值:

...
success: function (response) {
if(response.type == 1){
// do smth
}
else if(repsonse.type == 0){
// do another thing
}
},
...

最新更新