JQuery getJSON从Controller(代码点火器)检索数据的问题
我的JQuery,Ajax和PHP代码有问题。 我有一个页面,其中包含用户的所有post。 然后在这个页面中,我想使用Ajax加载该post的最新评论。 但它没有显示任何东西。
这是我调用JQuery函数的PHP代码:
Latest Comment:
var post_id = $('#post_id_').val(); document.write(post_id);//just to check that post_id value is not undefined $(function(){ $.getJSON("postC/latest_comment", {post_id: post_id}, function(res){ $("#result").prepend(res.text); }); });
这是我的PHP代码点火器控制器,处理请求:
class postC extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('models_facade'); $this->load->Database(); $this->load->helper('url'); $this->load->helper('form'); $this->load->library('tank_auth'); $this->load->library('user_session_lib'); error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); } function latest_comment(){ $post_id = $this->checkValues($_GET['post_id']); $latestcomment = $this->models_facade->getLatestCommentForPost($post_id); return json_encode($latestcomment); } }
我已经测试过手动调用该函数并显示最新的注释而不使用ajax,并且它工作正常。 所以这意味着模型中的后端函数从mysql中检索结果没有任何问题。
我也尝试过这样做:
echo json_encode($latestcomment);
当试图手动调用该函数时,我可以看到数据是JSON格式的。
所以这意味着,ajax调用有问题,它没有从控制器获取数据。 我使用GET代替.getJSON,POST代表.post()和.ajax()。
我已经尝试了所有版本的jQuery Ajax调用:.getJSON(),. post()和.ajax(),但都没有。 我确信相应的Jquery库已正确加载,因为我所有其他的ajax函数都可以正常工作。
有没有人知道错误可能是什么? 我已经调试了一整天,但没有结果。
谢谢
这就是我处理jQuery Codeigniter调用的方式,它对我有用。
试试这个jQuery:
$(function(){ $.post("postC/latest_comment", {post_id: post_id}, function(data){ $("#result").prepend(data.html); },'json'); });
PHP:
function latest_comment(){ $post_id = $this->checkValues($_GET['post_id']); $jsonData['html'] = $this->models_facade->getLatestCommentForPost($post_id); echo json_encode($jsonData); }
这将允许您将更多内容放入返回的JSON对象中。 我喜欢使用的一个技巧是向数组添加“失败”和“msg”值。 因此,如果需要通知用户,那么我可以告诉用户它失败了,也许是为什么。
希望有所帮助
// lance
我的猜测是你没有在配置文件中启用查询字符串,这可能对你有用,
JavaScript的:
$(function(){ $.getJSON("postC/latest_comment/" + post_id, function(res){ $("#result").prepend(res.text); }); });
并在PHP控制器中:
function latest_comment($post_id) { $post_id = $this->checkValues($post_id); $latestcomment = $this->models_facade->getLatestCommentForPost($post_id); // Better practise to put json header header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); return json_encode($latestcomment); }
这就是我处理jQuery Codeigniter调用的方式,它对我有用。
$(function(){ $.post("postC/latest_comment", {post_id: post_id}, function(data){ $("#result").prepend(data.html); },'json'); });
PHP:
function latest_comment(){ $post_id = $this->checkValues(**$_GET['post_id']**); $jsonData['html'] = $this->models_facade->getLatestCommentForPost($post_id); echo json_encode($jsonData); }
这将允许您将更多内容放入返回的JSON对象中。 我喜欢使用的一个技巧是向数组添加“失败”和“msg”值。 因此,如果需要通知用户,那么我可以告诉用户它失败了,也许是为什么。
希望有所帮助
在这个答案
$_POST['post_id']
在我的情况下工作正常,而不是$_GET['post_id']
我的朋友,我有一个类似的情况。 而不是使用返回编码json尝试回显结果。 你基本上需要的是一个现成的json数据文件和解析它的js脚本。 在您的情况下,结果只是浮动并等待在视图中回显。 希望能帮助到你。