jquery - parse json - 2 arrays
How to use each parse the json type -
retrieveMessage: function()
{
$.post('ActionScripts/RetrieveMessage.php',{
}, function(data) {
$.each(data, function(key, reader){
alert(reader.id + reader.count); //this line does not return anyt开发者_如何学编程hing
});
},"json");
}
data:
[{"id":"1","user_name":"Jenan","user_image":"ImageName","text_chat":"Hello","date":"2011-09-25 21:29:09","error":""}][{"count":"2"}]
I would get text -
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);
Here compose two collections together. How to read the collection with id parameters and collection of the count? Is this the right solution? What solution do I choose for composing arrays?
Thanks for the advice.
Instead of gluing 2 arrays together:
echo json_encode($jsonresult) . json_encode($count);
you should make one array that contains them:
echo json_encode(array(
'result' => $jsonresult,
'count' => $count
));
Now in your 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");
try
}, function(data) {
data = eval(data);
$.each(data, function(key, reader){
精彩评论