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.

    评论

报告相同问题?