使用jQuery从json_encode获取值

时间:2011-09-24 22:39:23

标签: javascript jquery json each

我在数据库表的一行中插入了几个(array)值和json_encode的值,现在希望用jquery将它们作为顺序回显。

这是我的PHP代码输出:

[{
    "guide": null,
    "residence": [{
        "name_r": "jack"
    }, {
        "name_r": "jim"
    }, {
        "name_r": "sara"
    }],
    "residence_u": [{
        "units": ["hello", "how", "what"],
        "extra": ["11", "22", "33"],
        "price": ["1,111,111", "2,222,222", "3,333,333"]
    }, {
        "units": ["fine"],
        "extra": ["44"],
        "price": ["4,444,444"]
    }, {
        "units": ["thanks", "good"],
        "extra": ["55", "66"],
        "price": ["5,555,555", "6,666,666"]
    }]
}]

我想作为(输出):

  

jack
hello& 11& 1,111,111
how& 22& 2,222,222
what& 33   &安培; 3,333,333,

  

jim
fine& 44& 4,444,444

  

sara
thanks& 55& 5,555,555
good& 66& 6,666,666

怎么回事?

1 个答案:

答案 0 :(得分:2)

假设

  • 您已经知道如何使用PHP脚本获取此信息的ajax请求
  • 顶层数组中总有一个元素(如果没有,你可以再增加一个迭代级别)
  • 按输出你的意思是访问相应的元素 - 我已经调用了console.log但你可以alert()或者放入DOM元素或其他什么

你可以在jQuery中做这样的事情(这里是没有网络部分的example fiddle。你会在你的控制台中看到输出)

var data = response[0]; //response is the data received by the jQuery ajax success callback
var residences = data.residence;
var residence_u = data.residence_u;

$.each(residences, function(index, val){
    var name = val.name_r;
    console.log(name);

    var info = residence_u[index]; //get the corresponding residence_u element

    $.each(info.units, function(index, val){
        var unit = val;
        var extra = info.extra[index];
        var price = info.price[index];
        console.log( val + " & " + extra + " & " + price);
    });
});