解析jquery ui自动完成的json数据

时间:2014-03-31 12:13:28

标签: javascript jquery json

我有一个json响应,如下面的

{"total":2,"data":[
            {"0":{"id":11,"name":"apple","image":"apple.png","description":"apple","status":1,"application_on":null,"created_at":"0000-00-00 00:00:00","updated_at":"1995-04-05 06:11:54",
        "fname":"apple","lname":"","profile_image":"<img src=\"\/pac\/public\/images\/brands\/60_60\/apple.png\"  \/>"},
            "1":{"id":16,"name":"chapstick","image":"chapstick.png","description":"chapstick","status":1,"application_on":null,"created_at":"0000-00-00 00:00:00","updated_at":"0000-00-00 00:00:00",
        "fname":"chapstick","lname":"","profile_image":"<img src=\"\/pac\/public\/images\/brands\/60_60\/chapstick.png\"  \/>"},"length":2}]}

我如何迭代这个并从中取出fname?提前谢谢。

我使用以下代码进行自动完成

$(".textfield1").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "<?php echo $this->baseUrl('admin/ajax/global-search/') ?>",
                data: {q: request.term, },
                dataType: "json",
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            value: item
                        };
                    }));
                }
            });
        }
    });

但它显示&#34; 0&#34;,obj etcc ..

2 个答案:

答案 0 :(得分:1)

这是你的success()函数的主体:

var a = [];
for ( var i in data.data  ) {
    for ( var j in data.data[i]  ) {
        if ( 'undefined' !== typeof data.data[i][j].fname ) {
            a.push(data.data[i][j].fname);
        }
    }
}
response(a);

答案 1 :(得分:0)

尝试更改为:

response($.map(data, function(item, index) {
    return {
        value: item[index.toString()]
    };
}));