2015-01-15 83 views
1

我有一个问题,使用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 { 
+0

无法发送这样的多个响应给他们所有,而不是responces增加和数组并一次发送全部 – Steve 2015-01-15 16:38:22

回答

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

谢谢,它现在很酷(y)! – Scorpion 2015-01-15 23:35:56

0

通过调用你的响应函数,你多次响应。从你的代码,我认为其目的是回应如下:

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

如果是这样的话,我的建议是在你的调用而言,以下结构,以提供相应的结果:

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

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