【发布时间】:2011-03-24 11:08:32
【问题描述】:
我的 JQuery、Ajax 和 PHP 代码有问题。
我有一个页面,其中包含来自用户的所有帖子。
然后在此页面中,我想使用 Ajax 加载该帖子的最新评论。
但是它没有显示任何内容。
这是我调用 JQuery 函数的 PHP 代码:
<? foreach($post_query as $post_row){ ?>
<li class="post_list">
<?php echo $post_row['text'];?>
<br/>
Latest Comment:
<br/>
<script type="text/javascript">
var post_id = $('#post_id_<?php echo $post_row['id'];?>').val();
document.write(post_id);//just to check that post_id value is not undefined
$(function(){
$.getJSON("<?php echo base_url();?>postC/latest_comment", {post_id: post_id},
function(res){
$("#result").prepend(res.text);
});
});
</script>
<? } ?>
这是我处理请求的 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 调用有问题,它没有从控制器获取数据。我对 .getJSON 使用 GET,对 .post() 和 .ajax() 使用 POST。
我已经尝试了所有版本的 jQuery Ajax 调用:.getJSON()、.post() 和 .ajax(),但都没有奏效。 我确信相应的 Jquery 库已经正确加载,因为我所有的其他 ajax 函数都可以正常工作。
有没有人知道错误可能在哪里?我已经调试了一整天,没有得到任何结果。
谢谢
【问题讨论】:
-
使用调试器检测我是否成功执行了AJAX调用以及回复是什么。
标签: php json codeigniter jquery