Need some help with json and jQuery
I cannot figure out json for whatever reason, i don't understand why i cannot get this to work.
my json is returning:
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
etc, etc, etc
now i am trying to retrieve it by using:
$.getJSON("lists.php",
{id: aid},function(data){
$.each(data.lists, function(i, info) {
$('.container').append(info.item+info.count);
});
});
but i don't get any data here. can anyone point开发者_JS百科 me in the right direction?
});
You need to return the data like this:
{
"lists":[
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}
In your php, do the following:
echo "{\"lists\":[";
foreach ($lists as $obj) {
echo "{\"item\": \"" . $obj->item . "\", ";
echo "\"count\": \"" . $obj->count . "\"},";
}
echo "]}\n";
Hope that helps!
It looks like you're used to how URL parameters are encoded. JSON works differently.
If you want your object to contain a key lists
which contains an array, you should return JSON like this:
{
"lists": [
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}
The above isn't valid JSON. I believe this is the syntax you are looking for, which would be described as "an object with a list property containing an array of items":
{"lists":[{"item":"1","count":"5"},{"item":"1","count":"5"},{"item":"1","count":"5",{"item":"1","count":"5"},{"lists":[{"item":"1","count":"5"}]}
You probably need to adjust your backend code so it's adding a new member to the "lists" array rather than an entirely new "lists" each time.
精彩评论