3

我有从数据库中获取数据的 codeigniter 应用程序,这些数据由 Jquery 操作。数据库中的结果数组曾经看起来像这样:

 { "result":[
    {"name":"John","surname":"Smith"}] }

我使用下面的代码来解析它:

$.get("index.php/getResult",{f_name: $('#fn').val()} ,function(data) {
    var list= "";
    $.each(data, function(index, element) {
        if (index > 0) {list;}
        list+= element.name;
    });
    $('#myid').html(list);
},"json");

我的结果数组已更改为以下格式,我现在如何解析它?任何帮助表示赞赏。

{
"count": 8,
"result":[
{"name":"John","surname":"Smith"}] }
4

2 回答 2

3

你不需要解析任何东西:

$.get("index.php/getResult",{f_name: $('#fn').val()} ,function(data) 
{
    alert(data.count);

    for(var i=0; i< data.result.length; i++)
    {
        alert(data.result[i].name + " " + data.result[i].surname);
        // etc.
    }
    // etc.

},"json");
于 2013-01-08T20:42:50.983 回答
1

当您使用 json (这意味着J ava S cript- O bject- Notation)时,您可以像使用任何其他 JavaScript 对象一样使用此对象。因此,您可以访问result[0].name例如。对于调试,我建议使用Firebug Add-On for Firefox 或Chrome Webdevelopertool。在这两者中,您都可以编写console.log(data)console.log(result[0].name)例如并在控制台选项卡中查看您的对象。

于 2013-01-08T20:59:33.923 回答