错误发送多个json消息

时间:2015-01-15 16:35:41

标签: php jquery ajax json

我和json有问题, 我有一个发送json数组的函数

public function repondMessage($etat=true,$message)
{
    $msg =  array($etat,$message);
    return '{"msg":'.json_encode($msg).'}';
}

并且只在发送一个错误时正确获取Json数组

像这样:

if(a=1)
{
echo respondeMessage(false,'Error');
}

和jQuery:

    console.log(data);
    var resp = jQuery.parseJSON(data);
    console.log(resp);

我得到的结果对我来说很好:

{"msg":[false,"Error"]}

但当我同时收到两条消息时,我就像那样进行测试

if(a=1)
{
echo respondeMessage(false,'Error');
}

if(b=1)
{
echo respondeMessage(false,'Error2');
}

发生了什么:(我不知道如何分离这两个Json)

{"msg":[false,"Error"]}{"msg":[false,"Error2"]}

    Uncaught SyntaxError: Unexpected token {

2 个答案:

答案 0 :(得分:0)

通过调用您的响应功能,您将多次响应。从您的代码中,我认为其目的是回应如下:

{"msg":[false, "Error", "Error2"]}

如果是这种情况,我建议您在调用上下文中使用以下结构来提供这些结果:

$errors = [];
if($a=1){
    $errors[] = 'Error';
}

if($b=1){
    $errors[] = 'Error2';
}
if( count( $errors ) ){
    respondMessage( true, $errors );
}

答案 1 :(得分:0)

根据我的评论,你不能发送多个回复,而是将响应添加到数组并立即发送它们

public function respondMessage($message)
{
    $msg =  array('msg'=>$message);
    //Always send the correct header
    header('Content-Type: application/json');
    echo json_encode($msg);
    //and stop execution after sending the response - any further output is invalid
    die();
}
$errors=[];
if($a=1)
{
    $errors[]=[false=>'Error'];
}

if($b=1)
{
    $errors[]=[false=>'Error2'];
}

if(!empty($errors){
    respondMessage($errors);
}
相关问题