Php jQuery POST处理错误

Php jQuery POST处理错误,php,jquery,Php,Jquery,解释 我正在发送一篇帖子,用PHP检查数据库中是否已经存在用户名。 如果是,则返回一个错误 但问题是,我不能使用相同的函数(data),因为我希望错误位于另一个div中 $.post("events.php?action=send", { data : $(this).serialize() }, function(data) { $("#processing").html(''); $("#comments").html(data); }); 问题 我不能在匿名函数中

解释

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

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

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


我不能在匿名函数中有两个变量,比如函数(数据,错误),那么我应该如何获取PHP打印的“错误”,例如“用户已经存在于数据库中”,然后将其放入#errors div?

在PHP中,您可以返回json错误,比如
打印“{”错误“:.json_encode($error)。},在js中输入所需的div

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

这取决于如何处理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);
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);
    }

}
JS:

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

}

我建议您以json字符串的形式从服务器返回数据。如果这样做,您可以从$.parseJSON(数据)获取一个对象

现在在匿名函数中:

// Javascript
data = $.parseJSON(data);
console.log(data);

if (data.userExists) alert("User exists!");

不要使用速记,使用
.ajax
有什么区别?什么jQuery版本?在最近的版本中,这一工作方式发生了变化。1.9.1.min是我的版本,类似于此解决方案!未捕获的TypeError:无法使用“in”运算符在中搜索“error”1@JonyKale可能是因为数据未定义,请尝试更新的代码。未捕获的TypeError:无法使用“in”运算符搜索“error”中的“error”呵呵呵呵“呵呵”是“data”中的内容。如果(data&&'error'in data){$(“.error”).html(data);}$.post(“events.php?action=send”,{data:$(this.serialize()},则函数(data)@JonyKale会让jquery知道您正在发送JSON数据,我假设您会这样做。