jQuery POST处理错误


jQuery POST handling errors

解释

我正在发送POST,并在PHP中检查数据库中是否已经存在用户名。如果是,则返回一个错误。

但问题是,我不能使用相同的function(data),因为我希望错误位于另一个分区中。

$.post("events.php?action=send", { data :  $(this).serialize() }, function(data) 
{
    $("#processing").html('');  
    $("#comments").html(data);
});

问题

我不能在匿名函数中有两个变量,比如函数(data,error(,那么我应该如何获取打印的"error"PHP,例如"User ready exists’s in database",然后将其放在#errorsdiv中?

这取决于您如何处理PHP代码中的错误。

为了最终进入错误处理程序,您需要将HTTP状态代码设置为"5XX"。

你可能想做的是序列化一个错误对象,以防用户已经存在,并像现在这样在成功处理程序中处理它:

PHP:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$data = array('error' => 'something went wrong');
echo json_encode($data);

JS:

function(data){
    if(data && data.error){
       //there was an error, handle it here
       console.log(data.error);
    } else {
       //do something else with the user
       console.log(data);
    }
}

在PHP中,您可以返回json错误,如print '{"error":'.json_encode($error).'}',然后在js中放入所需的div

$.post("events.php?action=send", { data :  $(this).serialize() }, function(data) 
{
  $("#processing").html('');
  $("#comments").html(data);
  $("#error").append(data.error);
});

我建议您将数据作为json字符串从服务器返回。如果您这样做,您可以从$.parseJSON(数据(;

// In your php code
$result = new stdClass();
$result->userExists=false;
echo json_encode($result);

现在进入您的匿名功能:

// Javascript
data = $.parseJSON(data);
console.log(data);
if (data.userExists) alert("User exists!");