How to handle and output right json array
My ajax request looks like this:
$.post('newsletter.php?mode=grab', { search: searchstring }, function(data) {
$('#newsletter_receivers').html(
data
);
});
Output from this is: (data)
{"id":"111","fullname":"Test Test","age":"31"}{"id":"112","fullname":"Max Max","age":"31"}{"id":"113","fullname":"12开发者_运维技巧3 123","age":"31"}{"id":"114","fullname":"Det Fungerar","age":"31"}
Now this is just putting this json in the div element for now.
But how can i extract each json array and output the fullname and age?
So it will appear as:
Test Test - 31
Max max - 31
In case your valid json looks like
[{"id":"111","fullname":"Test Test","age":"31"},{"id":"112","fullname":"Max Max","age":"31"},{"id":"113","fullname":"123 123","age":"31"},{"id":"114","fullname":"Det Fungerar","age":"31"}]
you can use
$.post('newsletter.php?mode=grab', { search: searchstring }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index,b){
$('#newsletter_receivers').append('<br>'+b.fullname+' - '+b.age);
});
});
I corrected your json wichi is not valid. You could do:
var json = [
{
"id": "111",
"fullname": "Test Test",
"age": "31"},
{
"id": "112",
"fullname": "Max Max",
"age": "31"},
{
"id": "113",
"fullname": "123 123",
"age": "31"},
{
"id": "114",
"fullname": "Det Fungerar",
"age": "31"}
];
var text = '';
$.each(json, function(index, b) {
text += b.fullname + ' - ' + b.age + '<br/>';
});
$('#newsletter_receivers').html(text);
fiddle here:
http://jsfiddle.net/4crnm/
for your example:
$.post('newsletter.php?mode=grab', { search: searchstring }, function(data) {
data = $.parseJSON(data);
var text = '';
$.each(data, function(index, b) {
text += b.fullname + ' - ' + b.age + '<br/>';
});
$('#newsletter_receivers').html(text);
});
That's not valid JSON. You'll need to turn it into an array or something. If you can't do it server side then try this:
$.post('newsletter.php?mode=grab', { search: searchstring }, function(data){
$('#newsletter_receivers').html('');
$.each($.parseJSON('['+data.replace(/\}\{/g, '},{')+']'), function(){
$('#newsletter_receivers').append('<div>'+this.fullname+' - '+this.age+'</div>');
});
});
If you can fix it server side that'd be a lot better of a solution.
change your jason to something like
{
"data": [
{
"id": "111",
"fullname": "Test Test",
"age": "31"
},
{
"id": "112",
"fullname": "Max Max",
"age": "31"
},
{
"id": "113",
"fullname": "123 123",
"age": "31"
},
{
"id": "114",
"fullname": "Det Fungerar",
"age": "31"
}
]
}
and access it like,
$(function(){
$.post("path/to/json",function(data){
$(data.data).each(function(i,j){
alert(data.data[i].fullname);
});
},'json');
});
whne you specify the dataType
as json
you dont need to do $.parseJSON
also you can verify your json at www.jsonlint.com
精彩评论