加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:51:40 所属栏目:百科 来源:网络整理
导读:该模型似乎与控制器一样有效. AJAX将结果显示为“null”,因此我认为这是因为我们需要将数据作为json发送.有关如何将数据转换为正确格式并在视图中显示的任何想法 视图 button type='button' name='getdata' id='getdata'Get Data./buttondiv id='result_tabl
该模型似乎与控制器一样有效. 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中显示的内容:

你好,世界

空值

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

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

解决方法

您可以使用$.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);
        })
    })
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读