2011-09-26 6 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 개의 배열입니다. –

답변

2

을 시도 :

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

당신이해야을 포함하는 하나 개의 배열 :

자바 스크립트에서 이제
echo json_encode(array(
    'result' => $jsonresult, 
    'count' => $count 
)); 

:

$.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을 자동으로 파싱합니다. –