模型似乎和控制器一樣工作。 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