【问题标题】:Unable to display JSON fromated database result using Jquery无法使用 Jquery 显示来自 JSON 的数据库结果
【发布时间】:2013-01-05 20:22:07
【问题描述】:

我有 Codeigniter 应用程序,它从数据库中获取数据作为结果数组,将数据转换为 Json 并显示结果。但是,我一直未定义为显示结果。

型号

 $this->db->where('product_name',$sid);
      //  $this->db->select('product_title');
        $res = $this->db->get('products');
         $data = $res->result_array();  
         return $data;

查看:

<script language="javascript">
    $('#findsubmit').click(function() {
        $.get("/products/index.php/find/lookup",{id : $('#id').val() },function(data) {

            $('#result').html('Product name: ' + data.product_name);
            //+ ' Last name: ' + data.lastname);
        },"json");
        return false;
});
</script>

我在 Firebug 中收到的结果数组:

[{"category":"camera","product_name":"Sony HX20"},{"category":"camera","product_name":"Canon SZ220"}]

如果我创建这样的简单数组一切正常:

return array('category' => 'camera','product_name' => 'Sony HX20');

我在 Firebug 中收到的结果数组:

{"category":"camera","product_name":"Sony HX20"}

【问题讨论】:

    标签: php jquery json codeigniter codeigniter-2


    【解决方案1】:

    在您的 JSON 数据中,您会收到一个包含多个结果的数组:data.product_name 未定义,但 data[0].product_namedata[1].production_name 已定义。

    您应该尝试仅返回一个结果(例如您手动构建的结果),或者在 data 上进行迭代。

    编辑:这是一个关于如何使用$.each的示例:

    var names = 'Product name: ';
    $.each(data, function(index, element) {
        if (index > 0) {names += '; ';}
        names += element.product_name;
    });
    $('#result').html(names);
    

    【讨论】:

    • 谢谢,现在它可以工作了。关于如何迭代数据的任何建议?只用for循环?
    • 你可以使用循环或者jQuery函数$.each
    • 谢谢。知道如何将它添加到我的代码中,因为我对 Jquery 还是很陌生。
    猜你喜欢
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多