刚开始使用此 Jquery AJAX 方法。所以我正在使用 Jquery 进行 AJAX 调用,在我的 PHP 脚本中,我正在检查数据库中的条件是否为真,然后再传入数据字符串并绑定(bind)变量,然后执行该查询。脚本和数据库插入都正常工作。
我的问题是,如何让它在 PHP 脚本返回时在 AJAX 调用中显示错误消息?
JS
<小时/>$.ajax({
type: "POST",
url: 'submit_form.php',
data: dataString,
error: function() { alert('Error'); },
success: function() { alert('Success'); }
});
SUBMIT_FORM.PHP
if ( count of rows in db < x )
{
return false;
exit();
}
<小时/>if this condition is true I want to stop execution of my script and execute the error condition in my AJAX function.
elseif ($stmt = $mysqli->prepare("INSERT INTO blah (stuff, morestuff) values (?, ?)")) {
/* Bind our params */
$stmt->bind_param("ss", $param1, $param1);
/* Set our params */
$param1= $_POST["name"];
$param2= $_POST["email"];
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
}
if the first condition is false then I want to return the success function in my ajax call which it is currently doing.
最佳答案
要调用 $.ajax
的错误处理程序,您可以在 PHP 中编写以下代码(对于 FastCGI):
header('Status: 404 Not found');
exit;
或者,如果您不使用 FastCGI,请使用 header('HTTP/1.0 404 Not Found')
。
我个人不会使用这种方法,因为它模糊了 Web 服务器错误和应用程序错误之间的界限。
您最好使用如下错误机制:
echo json_encode(array('error' => array(
'message' => 'Error message',
'code' => 123,
)));
exit;
在您的成功处理程序中:
if (data.error) {
alert(data.error.message);
}
关于php - Jquery AJAX 从 PHP 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13044082/