这个模型似乎和控制器一样有效。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
null
如果我直接访问网址 (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(variable)
来获取返回数据的良好想法。还可以使用 json viewer 进行轻松解析。 - Jakub