[英]Parse JSON json_encoded database results
Here is my code in controller. 这是我在控制器中的代码。 I want grab this results into ajax success part.
我想把这个结果变成ajax成功的一部分。 my question how to display results in ajax after using JSON.parse() function, can some one help me with loop;
我的问题是使用JSON.parse()函数后如何在ajax中显示结果,有人可以帮我循环吗? json code is something like this
[{'id:1'},{info:name}]
??? 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 part 阿贾克斯部分
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);
// });
}
});
just change 只是改变
dataType: "text",
to 至
dataType: "json",
and jQuery is doing the parsing. jQuery正在进行解析。
[EDIT] [编辑]
supposed you have: [{'id':1,'info':'name'},{'id':2,'info':'nom'} ]
(your json in your post is slightly unusable and not the result of an json_encode of an array) ... 假定您具有:
[{'id':1,'info':'name'},{'id':2,'info':'nom'} ]
(您帖子中的json稍微不可用,而不是结果数组的json_encode)...
success: function(msg){
var id = msg[0].id;
var info = msg[0].info;
...
There's no error handling and no exception handling in this code which I regard as necessary! 我认为在此代码中没有错误处理和异常处理!
First remove that dataType form your $.ajax(), and then add a correct content-type header in php like: 首先从$ .ajax()中删除该dataType,然后在php中添加正确的content-type标头,例如:
header('Content-type: application/json');
This way, jQuery will parse your json correctly. 这样,jQuery将正确解析您的json。
Now, you can do something like: 现在,您可以执行以下操作:
success: function(res){
$.each(res, function(el) {
console.log(el.id);
console.log(el.info);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.