模型似乎和控制器一样工作。 AJAX将结果显示为“null”,所以我认为这是因为我们需要将数据作为json发送。如何将数据放到正确的格式,并在视图使用AJAX,jquery和codeigniter显示数据库中的数据
查看
<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"
},
}
我如何提取此信息并显示我想显示什么?
使用'console.log(变量)'来获得返回的数据的好主意。还可以使用[json viewer](http://jsonviewer.stack.hu/)轻松解析 – Jakub