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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21055824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:24:55  来源:igfitidea点击:

Displaying data from database with AJAX, jquery and codeigniter

jqueryajaxcodeigniter

提问by user2796352

The model seems to be working as well as the controller. The AJAX displays the results as "null" so I think it is because we need to send the data as json. Any ideas on how to get the data into the correct format and to display in the view

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

View

看法

<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>

Controller

控制器

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;
}

Model

模型

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
    }
}

Okay so the AJAX returns the success alert, however instead of displaying the table from the database, this is what is displays in the div:

好的,所以 AJAX 返回成功警报,但是不是显示数据库中的表,而是显示在 div 中的内容:

Hello World

你好,世界

null

空值

If I go directly to the url (http://loca.lhost:8888/index.php/trial/getValues) this is the object that appears:

如果我直接访问 url ( 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"
    },

  }

How do I extract this info and display what I want to display?

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

采纳答案by Pranav C Balan

You can extract data from the json by using $.each

您可以使用从 json 中提取数据 $.each

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);
        })
    })
}

回答by Jakub

You're overcomplicating some things, update this to just output json:

您使某些事情过于复杂,请将其更新为仅输出 json:

controller:

控制器:

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) );
    }
}

and your javascriptwill easily handle the result (since you pass back JSON = javascript object notation)

并且您的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
    }
}

Using var re = $.parseJSON(data);will easily let you access the json data in .form:

使用var re = $.parseJSON(data);将轻松让您以以下.形式访问 json 数据:

re.resultetc;

re.result等等;

Output the json to console.log(data)to see its structure (without printing it into your html). Use Chrome inspector to traverse your structure.

输出 json 以console.log(data)查看其结构(无需将其打印到您的 html 中)。使用 Chrome 检查器遍历您的结构。

回答by MY_Mark

Rather than returning $datafrom your controller, json_encodeit and use echoinstead.

而不是$data从您的控制器返回,json_encode而是使用它echo

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

Hope that helps!!

希望有帮助!!