简体   繁体   English

无法显示Ajax值

[英]Can't display Ajax value

I have a problem with my ajax, it can't display data from database. 我的Ajax有问题,它无法显示数据库中的数据。

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 . 当我使用val() ,结果为[object Object] ;当我使用html() ,结果为 But when I use console.log(data) it works. 但是当我使用console.log(data)它可以工作。

Just convert json object to string and it will work. 只需将json对象转换为字符串,它将起作用。

$('#aaaa').val(data.someVar);

For example, 例如,

var jsonVal = {val1:'one',val2:'two'};
alert(jsonVal); // it will print [object][object]
alert(jsonVal.val1); // one
alert(jsonVal.val2); // two
alert(JSON.stringify(jsonVal)) // it will print {val1:'one',val2:'two'}

Hope it will help you. 希望对您有帮助。

You need to first decode the json in your ajax success. 您需要在ajax成功中首先解码json。

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. 使用此功能,您可以访问数据中的不同值,并在html中设置值。

Update 更新

In your controller you can return the value using json_encode like 在您的控制器中,您可以使用json_encode返回值,例如

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 在ajax成功函数中,可以使用msg1的值

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. 通过这种方式,您可以访问json对象中的每个值。

You have to require $.pasrseJSON before use the data 您必须先使用$ .pasrseJSON才能使用数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM