【问题标题】:Jquery AJAX return from PHP从 PHP 返回的 Jquery AJAX
【发布时间】:2012-10-14 04:33:46
【问题描述】:

使用此 Jquery AJAX 方法的新手。因此,我正在使用 Jquery 进行 AJAX 调用,在我的 PHP 脚本中,我正在检查数据库中的条件是否为真,然后再传入我的数据字符串并绑定变量,然后执行该查询。脚本和数据库插入都可以正常工作。

我的问题是,我怎样才能让它在我的 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();

}

如果此条件为真,我想停止执行我的脚本并执行 我的 AJAX 函数中的错误情况。


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(); 
}

如果第一个条件为假,那么我想在我当前正在执行的 ajax 调用中返回成功函数。

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

要调用您的$.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);
}

【讨论】:

    【解决方案2】:

    如果你想在 jquery 中执行错误命令,你可以尝试使用: throw new Exception("Invalid"); 在你的 php 代码中(应该调用错误)。

    这将导致 http 服务器向您的 javascript 代码返回错误代码 500。

    【讨论】:

      【解决方案3】:

      你的概念是错误的。错误条件意味着 ajax 调用中的错误 将您的代码更改为此

      $.ajax({
      type: "POST",
      url: 'submit_form.php',
      data: dataString,
      error: function() {
       alert('Error'); //here the error is the error in ajax call.eg failing to call or a 404..etc
       },
      success: function(msg) {
      if(msg=='error'){
         alert('Error'); //this is the error you are looking for
      }else{
       alert('Success'); 
      }
      
      }
      });
      

      你的 PHP

      if ( count of rows in db < x  )
       {
      echo 'error'; //this is  enough
      exit;
      
      }
      

      【讨论】:

        【解决方案4】:

        我认为你对 jquery 错误设置有点困惑,根据 jquery

        error : 请求失败时调用的函数。

        所以您的错误代码只会因为以下原因而被触发

        404 错误 - ajax 文件未找到错误

        500 错误 - ajax 内部系统错误

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多