发送多条 json 条消息时出错

Error Sending multiple json messages

我对 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 {

通过调用您的响应函数,您可以多次响应。根据您的代码,我相信其意图是响应如下:

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

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

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

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

根据我的评论,您不能发送多个回复,而是将回复添加到数组并一次发送所有回复

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