发送多个 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 {

根据我的评论,您不能发送多个响应,而是将响应添加到和数组并一次发送它们

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

通过调用响应函数,您可以多次响应。 从您的代码中,我相信意图是按如下方式响应:

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

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

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