使用AJAX、jQuery和CodeIgniter从数据库中显示数据

4

这个模型似乎和控制器一样有效。AJAX显示的结果是“null”,我认为这是因为我们需要将数据发送为json格式。您有任何想法如何将数据转换为正确的格式并在视图中显示吗?

视图

<button type='button' name='getdata' id='getdata'>Get Data.</button>

<div id='result_table' style="color:white;">
hola amigo
</div>

<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
                $.ajax({
                        url: 'http://localhost:8888/index.php/trial/getValues',
                         type:'POST',
                         dataType: 'json',
                          error: function(){
                          $('#result_table').append('<p>goodbye world</p>');
                          },

                         success: function(results){


                       $('#result_table').append('<p>hello world</p>' +results);
                       alert("Success!");

                          } // End of success function of ajax form
                          }); // End of ajax call

                });
</script>

控制器

function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($data));
    return $data;
}

模型

class Get_db extends CI_Model{
    function getAll(){
        $query=$this->db->query("SELECT * FROM questions");
        return $query->result();
        //returns from this string in the db, converts it into an array
    }
}

好的,所以 AJAX 返回了成功提示,但是它在 div 中显示的不是来自数据库的表格,而是以下内容:

Hello World

null

如果我直接访问网址 (http://loca.lhost:8888/index.php/trial/getValues) ,则会出现以下对象:

{
  "results": [
    {
      "qID": "1",
      "email": "hello",
      "qText": "hello",
      "playlistID": "",
      "timestamp": "0000-00-00 00:00:00"
    },
    {
      "qID": "2",
      "email": "",
      "qText": "",
      "playlistID": "",
      "timestamp": "0000-00-00 00:00:00"
    },

  }

我该如何提取此信息并显示所需要的内容?

使用 console.log(variable) 来获取返回数据的良好想法。还可以使用 json viewer 进行轻松解析。 - Jakub
3个回答

4
您可以使用 $.each 从 json 中提取数据。
success:function(data){
    $('#result_table').append('<p>hello world</p>');
    alert("Success!");
    $.each(data.results, function(k, v) {
        $.each(v, function(key, value) {
            $('#result_table').append('<br/>' + key + ' : ' + value);
        })
    })
}

1
不要从您的控制器返回$data,而是使用json_encode并使用echo
function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();
    echo json_encode($data);
}

希望有所帮助!

嘿,谢谢你的回复。看看我刚刚做的修改 :) - user2796352

1
你过于复杂化了一些事情,将其更新为仅输出json:
控制器:
function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();

    if($data['result']){   // we got a result, output json
         echo json_encode( $data['result'] );
    } else {
         echo json_encode( array('error' => true) );
    }
}

你的JavaScript将轻松处理结果(因为你返回JSON = JavaScript对象表示法)

success: function(data){
    // handle the result
    var re = $.parseJSON(data);

    if(!re.error){
        // no error so lets put out some data whatever way
    }
}

使用 var re = $.parseJSON(data); 可以轻松地让您以 . 的形式访问json数据: re.result 等;
将 json 输出到 console.log(data) 以查看其结构(而无需将其打印到您的html中)。 使用Chrome检查器遍历您的结构。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接