php - Jquery AJAX 从 PHP 返回

标签 php jquery ajax

刚开始使用此 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/

相关文章:

php - 我正在自学 PHP,并且已经了解 strip_tags() 函数。这是提高安全性的唯一方法吗?

php - 我正在使用 Laravel 5,但无法使用 php artisan migrate 迁移我的数据库

PHP创建表错误1064

JQuery 添加类到菜单

javascript - 用jquery动态判断某个类的哪个按钮被点击

javascript - HTML,如何并行设置图像的多个src属性,最快获胜

php - 如何避免在 php mysqli 中插入重复记录?

javascript - 用 JS 解析 JSON foreach,显示 HTML 列表

javascript - 使用 AJAX 登录,其中数据位于文本文件中

javascript - 无法获取从 PHP 到 $.ajax 的 JSON 回显