这是我在 Controller 中的代码。我想将此结果放入 ajax 成功部分。我的问题是如何在使用 JSON.parse() 函数后在 ajax 中显示结果,有人可以帮我解决循环问题吗? json 代码是这样的 [{'id:1'},{info:name}]
???
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$query = $this->db->get('pages');
$data = array();
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
}
$json = json_encode($data);
echo $json;
}
ajax部分
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
alert(msg);
// $.each($.parseJSON(msg), function() {
// $('#results_box').html(this.id + " " + this.info);
// });
}
});
最佳答案
改变一下
dataType: "text",
至
dataType: "json",
并且 jQuery 正在进行解析。
[编辑]
假设你有:[{'id':1,'info':'name'},{'id':2,'info':'nom'}]
(你的json在你的帖子中有点无法使用,而不是数组的 json_encode 的结果)
...
success: function(msg){
var id = msg[0].id;
var info = msg[0].info;
...
这段代码中没有错误处理和异常处理,我认为这是必要的!
关于javascript - 解析 JSON json_encoded 数据库结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25854643/