weixin_33724059 2018-03-19 05:45 采纳率: 0%
浏览 22

无法显示Ajax值

I have a problem with my ajax, it can't display data from database.

Controller

public function rating() {
 $rating = $this->db->select_avg('hasil_rating')
                    ->get('tb_rating')->row_array();
 echo json_encode($rating);
}

Ajax

function rate() {
 $.ajax({
  type: 'POST',
  url: '<?php echo base_url()."rate/rating"?>',
  dataType: 'json',
  success: function(data) {
    $('#aaaa').val(data);
  }
});

input

<input id="aaaa" type="text" value="">

when I used val() the result is [object Object] and when I used html() the result is empty. But when I use console.log(data) it works.

  • 写回答

3条回答 默认 最新

  • weixin_33736048 2018-03-19 05:47
    关注

    You need to first decode the json in your ajax success.

    Use this.

    function rate() {
     $.ajax({
      type: 'POST',
      url: '<?php echo base_url()."rate/rating"?>',
      dataType: 'json',
      success: function(data) {
        var d = $.parseJSON(data);
        $('#aaaa').val(d.value);
      }
    });
    

    Using this you can access different values from data and set the value in your html.

    Update

    In your controller you can return the value using json_encode like

    echo json_encode(array("success"=>true,"msg1"=>"test ajax","msg2"=>"test ajax 2"));
    

    In your ajax success function to get the value of msg1 you can use

    var d = $.parseJSON(data);
    alert(d.msg1); //will return "test ajax"
    alert(d.msg2); //will return "test ajax 2"
    

    By this way you can access each and every value from your json object.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度