2015-01-15 151 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); 
}