使用AJAX,jquery和codeigniter显示数据库中的数据

时间:2014-01-10 22:43:17

标签: jquery ajax codeigniter

该模型似乎与控制器一样有效。 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

如果我直接转到网址(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"
    },

  }

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

3 个答案:

答案 0 :(得分: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 :(得分:1)

而不是从您的控制器返回$datajson_encode而是使用echo

function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();
    echo json_encode($data);
}

希望有所帮助!!

答案 2 :(得分: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检查器遍历您的结构。