我创建了一个类似于社交媒体的小应用,人们可以在其中创建“状态更新”并对其进行评论。我使用PHP从数据库中提取所有“状态更新”,并使用PHP的foreach()
循环显示它们。jQuery AJAX在呼叫成功后再次加载确切的div
我的目标是每次用户发布评论时,它都会将评论存储在数据库中而不刷新页面(明显),然后再次加载ul.comments。问题是,因为我使用foreach()循环获取这些状态更新,所以有几个ul.comments,我的当前JS脚本无法确定哪些ul.comments需要更新。
这里是我的加价部分(仅注释部分):
<?php if($comments = $this->comment_model->getComments($event['event_id'])):?>
<?php foreach($comments as $comment):?>
<ul class="comments">
<li>
<a href="<?=base_url()?>user/<?=$comment['user_id']?>">
<img class="comment-img" src="<?=base_url()?>public/images/uploads/<?=$comment['profilepic']?>" alt="prof-img"/>
</a>
<a href="<?=base_url()?>user/<?=$comment['user_id']?>">
<span class="comment-name"><?=$comment['name']?></span>
</a>
<span class="comment-comment"><?=$comment['comment']?></span>
<?php if($comment['user_id'] == $this->session->userdata('user_id') || $this->session->userdata('user_type') == 1):?>
<a href="<?=base_url()?>comments/delete/<?=$comment['id']?>">Delete</a>
<?php endif?>
<span class="comment-date"><?=date('d.m.Y G:i', strtotime($comment['commented_at']))?></span>
</li>
</ul>
<?php endforeach ?>
<?php endif?>
这是我的AJAX调用张贴评论:
$("form.add-comment").on('submit', function(e) {
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
dataType: 'json',
beforeSend: function() {
from.find(".comment_submit").hide();
from.find("#spinner_comment").show();
},
success: function(data) {
if(data.st == 0) {
for(var key in data.msg) {
console.log(data);
}
}
if(data.st == 1) {
$("#event_comment").val('');
$.get(window.location,function(data){
$data = $.parseHTML(data);
$("ul.comments",from).html($("ul.comments",$data).html());
});
}
}, complete: function() {
from.find("#spinner_comment").hide();
from.find(".comment_submit").show();
}
});
e.preventDefault();
});
而这里的我的CI控制器/张贴评论的方法
public function add() {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->form_validation->set_rules('event_comment', 'Comment', 'required|htmlspecialchars');
if($this->form_validation->run() === false) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('st' => 0)));
return false;
} else {
$data = array (
'event_id' => $this->input->post('event_id'),
'user_id' => $this->session->userdata('user_id'),
'comment' => $this->input->post('event_comment')
);
$add_comment = $this->comment_model->addComment($data);
}
if($add_comment === true) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('st' => 1)));
return false;
} else {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('st' => 0)));
return false;
}
}
}
没什么..这将它添加到数据库中,但我只能看到新的评论,如果我刷新页面。在“开发者工具”中,如果我打开“网络”>“预览”选项卡,我只能查看从服务器获得的JSON – Cooper 2014-09-24 01:23:46
看看我的编辑,不知道我是否清楚 – 2014-09-24 01:26:44
在您的控制台中,它是在帖子后获取网址吗? – 2014-09-24 01:27:25