2011-09-26 60 views
1

如何使用每一個解析JSON類型 -jQuery的 - 解析JSON - 2個陣列

retrieveMessage: function() 
    { 

     $.post('ActionScripts/RetrieveMessage.php',{ 

     }, function(data) { 

      $.each(data, function(key, reader){ 

     alert(reader.id + reader.count); //this line does not return anything 

      }); 

     },"json"); 
    } 

數據:

[{"id":"1","user_name":"Jenan","user_image":"ImageName","text_chat":"Hello","date":"2011-09-25 21:29:09","error":""}][{"count":"2"}] 

我會得到的文本 -

id=1 count=2 

PHP

$jsonresult = array(); 

$count = array(); 
$countresult = array(); 
$countresult["count"] = "2"; 
$count[] = $countresult; 
while($row = mysql_fetch_array($result)) 
{ 
$thisResult = array(); 

$thisResult["user_auth"] = 1; 
$thisResult["id"] = $row['id']; 
$thisResult["user_name"] = $row['user_name']; 
$thisResult["user_image"] = $row['user_image']; 
$thisResult["text_chat"] = $row['text_chat']; 
$thisResult["date"] = $row['date']; 
$thisResult["error"] = ""; 

$jsonresult[] = $thisResult; 
} 
    echo json_encode($jsonresult) . json_encode($count); 

這裏組合兩個藏品。 如何讀取具有id參數和收集計數的集合?這是正確的解決方案嗎?我選擇哪種解決方案來組成陣列?

感謝您的意見。

+1

這不是有效的JSON,你不能只有一個接一個地接下來的兩個數組。你有權修改返回的JSON嗎? –

+1

@kingjiv,它是有效的JSON,但它是廢話。您可以在數組的每個索引中擁有不同的結構化元素,但這實際上表明實現服務器部分的人的設計非常糟糕。 –

+1

@DarinDimitrov:我不同意。將它粘貼到http://jsonlint.com/它只是2個數組相鄰,而不是1個對象或數組。 –

回答

2

而是膠合2列在一起:

echo json_encode($jsonresult) . json_encode($count); 

你應該做一個數組,其中包含他們:

echo json_encode(array(
    'result' => $jsonresult, 
    'count' => $count 
)); 
在JavaScript

現在:

$.post('ActionScripts/RetrieveMessage.php', {}, function(data) { 
    var result = data.result; 
    var count = data.count; 

    $.each(result, function(k,v){ 
     alert(v.id+' '+count[k].count); // 1 2 
    }); 
},"json"); 
+0

count [k]未定義 – Jenan

+0

@Jenan:'console.log'' result'和'count'來查看它們的實際結構是什麼,我不確定。 –

0

嘗試

}, function(data) { 
     data = eval(data); 
     $.each(data, function(key, reader){ 
+1

'eval'在這裏是不需要的。 ',「json」);'如果它有效的話,會自動爲你解析JSON。 –