dpir3950 2011-02-26 15:57
浏览 69
已采纳

让jQuery.ajax将响应解释为错误

I'm struggling to understand how to get jQuery.ajax to interpret a failed MySQL UPDATE query as an error. Here's my code:

jQuery:

$.ajax({
    type:'POST',
    url:'/ajax/registration.php',
    data:{formData: formData},
    success:function(data){eformDef.forms.registration.success(data);},
    error:function(data){eformDef.forms.registration.success(data);}
});

PHP

$data = $_POST['formData'];
$firstName = mysql_real_escape_string($data['first name']);
$lastName = mysql_real_escape_string($data['last name']);
$email = mysql_real_escape_string($data['email address']);
$password = mysql_real_escape_string($data['password']);


mysql_query("INSERT INTO users (first_name, last_name, email, password) VALUES ('$firstName', '$lastName', '$email', '$password')") or die(mysql_error());

No matter what--even if I make the mysql_query syntax invalid--the ajax call always interprets the response as a success. I assume that's because the mysql_error() gets sent back as the response, the ajax call reads that as a string, and apparently considers that to be a success. Of course I can deal with this by checking the response string in the $.ajax success function, but this seems a bit illogical. In cases where I can test for a data type using the $.ajax dataType option, this isn't an issue. But with an UPDATE query like the one above, I always get a string as a response.

Since there is a workaround (checking the string in the success function), this isn't a critical issue. But if there is a more correct way of doing this, I'd much prefer that.

  • 写回答

2条回答 默认 最新

  • dongxiaoxiao1983 2011-02-26 16:02
    关注

    PHP will send a 200 OK status no matter what*, so there is no way to jQuery to detect an error.

    You have two possibilities:

    • Have the PHP script explicitly output something like "OK" or an JSON encoded array with a status code. Have the jQuery side explicitly look for that "OK" and throw an error if it's not present.

    • Have the PHP script throw an error status code if an error occurs, for example:

        $query = mysql_query(......);
      
        if (!$query)
         {
           header("HTTP/1.1 500 Internal Server Error");
           echo mysql_error(); // Detailed error message in the response body 
           die();
         }
      

    * Except for this exception.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题