JQuery Ajax PHP中的错误和成功处理


Error and Success Handling in JQuery Ajax PHP

如何在Ajax中处理错误和成功消息?我有一个ajax调用,将我的数据保存到数据库中。我的php脚本首先检查用户是否有x数量。如果他小于x,那么他应该发出警报(数量<x),否则插入db。

我的php文件:

 ...
 .....
 if ($wallet_amount < "100") {
     $wa1 = 0;
     echo $wa1;
 } else {
     $inito = $connection->prepare("INSERT INTO bs (title, start, end, userid, typ, code) VALUES (:title, :start, :end, :pid, :col, :code)");
     $inito->bindValue(':pid', $pid, PDO::PARAM_INT);
     $inito->bindValue(':title', $title, PDO::PARAM_STR);
     $inito->bindValue(':start', $start, PDO::PARAM_STR);
     $inito->bindValue(':end', $end, PDO::PARAM_STR);
     $inito->bindValue(':col', $col, PDO::PARAM_STR);
     $inito->bindValue(':code', $code, PDO::PARAM_INT);
     $inito->execute();
     exit();        
} 

我的js文件:

$.ajax({
    url: 'add.php',
    data: {
        'title': $('#Name').val(), 
        'start': start, 
        'end': $('#End').val(), 
        'code': $('input[name="code"]:checked').val()
    },
    type: "POST",
    error: function () {
        alert('There was an error while adding events.');
    }
});

我的第一次尝试失败了。我写这样的东西:

 success: function (response) {
            if (response === 0) {
                alert("Amount < X!");
            } else if (response === 1) {
                alert("Amount > X);
            }
        },
        error: function () {
            alert('There was an error while adding events.');
        }

我猜在成功块中,您使用了严格的检查===,这会检查类型和值:

success: function (response) {
        if (response === '0') { // update this 
            alert("Amount < X!");
        } else if (response === '1') {
            alert("Amount > X"); //<---quote is missing i guess it's just a typo.
        }
    },
    error: function () {
        alert('There was an error while adding events.');
    }

此外,我不确定这种检查} else if (response === '1') {是否会发生,因为我不知道你是否在响应中得到了'1'

为了让代码更干净一点,我建议您首先用json返回值(即使它只是一个变量)

所以PHP看起来像

php

/* ... */
echo json_encode(array('wal' => $wal));
/* ... */

接下来,在您的ajax代码中,您需要正确地阅读它。例如

ajax

success: function(response) {
    var wal = response.wal
    if (wal == 0) {
        alert("Amount < X!");
    } else if (wal == 1) {
        alert("Amount > X);
    } else {
        // ...
    }
}

尝试一下,正如Jai所说,只检查值,而不检查类型(x==0而不是x==0)

我不会使用响应的内容来切换错误和成功案例。想想不同的状态代码,例如成功时的状态代码200204,错误时的状态码400。相比之下,您还可以使用显式返回值对更安全的应用程序进行编码:

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});