该模型似乎与控制器一样有效.
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); }) }) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。