Ajax返回错误调用错误Ajax错误调用

Ajax return error to call error ajax error call

本文关键字:错误 Ajax 调用 返回      更新时间:2023-09-26

我有一个ajax函数更新我的数据库..该函数工作得很好,更新数据库后,我调用了我创建的successAlert()函数。但是现在我想在错误的情况下调用错误函数,但是在测试中故意打破代码,我仍然得到successAlert()。

Ajax/Javascript:

var share = "test"
var custid = "test"    
$.ajax({
            url: "assets/ajax/customer-rec.php",
            type: "POST",
            data: {UpdateAccount: "yes",custid: custid,share: share},
            success: function(result){
                successAlert()      
            },
            error: function(result){
                errorAlert()    
            }
        });

PHP更新数据库

if (isset($_POST['UpdateAccount'])){
    $custid = $_POST['custid'];
    $share = $_POST['share'];
    $query="UPDATE `users` SET `share_ord`='$share' WHERE id= $custid";
    $stmt = mysql_query($query);
    if($stmt === false){
        return false
    }
}

返回false不是错误。如果您想发送错误,请使用

之类的标头
header('X-PHP-Response-Code: 404', true, 404);

你可以在success中调用同样的errorAlert()函数,这样

$.ajax({
        url: "assets/ajax/customer-rec.php",
        type: "POST",
        data: {UpdateAccount: "yes",custid: custid,share: share},
        success: function(result){
            if(result === false){
               errorAlert()
            } else  {
               successAlert()
            }      
        },
        error: function(result){
            errorAlert()    
        }
    });

要获得错误,您需要从为您的请求提供服务的php函数返回状态码'404'。

当服务器返回一个表示错误的HTTP状态码时,error回调被触发,因此您应该发送一个,例如HTTP 500

if($stmt === false){
    header('HTTP/1.1 500 Server error');
}

查看HTTP状态码列表

.ajax()将调用成功方法,因为一旦您的请求被服务器成功处理,那么它将向客户端重新运行HTTP_OK,如果.ajax没有接收到HTTP_OK,那么它将调用错误。根据您的代码,它将调用success,因为url存在,并且服务器将向浏览器发送HTTP_OK。如果你想生成error:,然后给出错误的url或断开互联网或简单地更改

PHP:

if($stmt === false){
      //If you want really generate some http error.
       header('X-PHP-Response-Code: 500', true, 500);
       exit(0);
      //or else continue as per code
      // return false;   
    }

在你的JS:

$.ajax({
        url: "assets/ajax/customer-rec.php",
        type: "POST",
        data: {UpdateAccount: "yes",custid: custid,share: share},
        success: function(result){
            if(!result){
               showErrorAlert()
            } else  {
               showSuccessAlert()
            }      
        },
        error: function(result){
            showErrorAlert()    
        }
    });