我撰寫了一些代碼,使用 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
uj5u.com熱心網友回復:
檢查查詢結果,如果成功則將某個值回傳給 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 ($cancelOrderResult) {
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
}
},
...
uj5u.com熱心網友回復:
更新:
我發現如果我向成功函式添加一個引數,它會在發生錯誤時填充錯誤文本。如果一切正常,文本就是“”。所以除了檢查它我什么都不用做:)
success: function(data)
{
if(data == "") result = true;
else result = false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334939.html
上一篇:使用jQuery動態更改文本
