如何处理和输出正确的json数组

时间:2011-08-28 09:30:57

标签: jquery ajax

我的ajax请求如下所示:

$.post('newsletter.php?mode=grab', { search: searchstring }, function(data) {
    $('#newsletter_receivers').html(
            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"}

现在这只是将这个json放在div元素中。

但是我如何提取每个json数组并输出fullname和age?

因此它将显示为:

Test Test - 31
Max max - 31

4 个答案:

答案 0 :(得分:1)

如果您的有效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"}]

你可以使用

$.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);
    });
});

答案 1 :(得分:0)

将你的杰森变成类似

的东西
{
    "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"
        }
    ]
}

并访问它,

$(function(){
 $.post("path/to/json",function(data){
  $(data.data).each(function(i,j){
  alert(data.data[i].fullname);
  });
  },'json');
});

你指定dataTypejson你不需要做$.parseJSON你也可以在www.jsonlint.com验证你的json

答案 2 :(得分:0)

这不是有效的JSON。你需要将它变成数组或其他东西。如果您无法在服务器端执行此操作,请尝试以下操作:

$.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>');
    });
});

如果您可以修复服务器端,那么解决方案会更好。

答案 3 :(得分:0)

我纠正了你的无效json。你可以这样做:

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);

在这里小提琴:

http://jsfiddle.net/4crnm/

为您的例子:

$.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);
});