dsf6281 2013-01-05 20:22
浏览 22
已采纳

无法使用Jquery显示JSON格式的数据库结果

I have Codeigniter application which fetches data from database as result array, converts data to Json and displays the results. However I keep getting undefined as display result.

Model

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

View:

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

Resulting array I receive in Firebug:

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

If I create simple array like this all works fine:

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

Resulting array I receive in Firebug:

{"category":"camera","product_name":"Sony HX20"}
  • 写回答

1条回答 默认 最新

  • douqilai4263 2013-01-05 20:50
    关注

    In your JSON data, you receive an array of several results: data.product_name is not defined, but data[0].product_name and data[1].production_name are.

    You should try to either return only one result (like the one you build manually), or iterate on data.

    Edit: here's a sample on how to use $.each:

    var names = 'Product name: ';
    $.each(data, function(index, element) {
        if (index > 0) {names += '; ';}
        names += element.product_name;
    });
    $('#result').html(names);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态