我在帖子数上显示ajax点赞,但是问题是,当我单击“点赞按钮”时,点赞(不加载页面)仅显示在第一篇文章上,而当我刷新页面时,所有点赞都单独显示的地方。 我想在特定帖子上显示ajax,而不仅仅是在第一个。我想我需要在成功函数中传递ID,但我不知道如何。这是代码。 在我的代码中:“谣言”就是一个帖子,“赞” =批准,“不喜欢” =不批准。
查看Ajax + HTML视图的特定部分
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
if (true) {
$('#showapp').html(val);
} else {
// <?php //echo base_url('Login'); ?>;
alert("You need to Login");
}
}
});
}
<span class="like-listing fll approve" onclick="approve_rumor(<?php echo $rumors->rumor_id; ?>)">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</span>
<span id="showapp" class="fll"><?php echo $rumors->rumor_totalapprovals ?></span>
控制器
function approve_rumor() {
if ($this - > session - > userdata('user_email', 'user_id')) {
$this - > load - > model('rumor_model');
$r_id = $this - > input - > post('r_id');
$data['user_id'] = $this - > session - > userdata('user_id');
$data['rumor_id'] = $r_id;
$this - > rumor_model - > ApproveRumor($data);
//$this->load->view('home1',['approval'=>$approval]);
} else {
return redirect('Login');
}
}
function ApproveRumor($data) {
// echo "<pre>";
// print_r($data);
// exit;
$r_id = $data['rumor_id'];
$query = $this - > db - > insert('approval', $data);
if ($query) {
$a = $this - > db - > query("SELECT * , count(rumor_id) as count_like FROM approval WHERE rumor_id = $r_id ");
echo "<pre>";
print_r($a - > row() - > count_like);
$totalapprovals = $a - > row() - > count_like;
$this - > db - > query("UPDATE rumors SET rumor_totalapprovals = $totalapprovals WHERE rumor_id = $r_id");
// echo $totalapprovals;
// $this->db->where('rumors.rumor_id',$r_id);
// $res = $this->db->update('rumors',$totalapprovals);
} else {
echo "0";
}
}
答案 0 :(得分:0)
我发现将数据传递到$ .ajax回调函数的一种很酷的方法是添加一个自定义选项,然后在$ .ajax回调中将其引用为this.optionProp:
$.ajax({
type: "post",
url: "your/url/here",
data: {
r_id: r_id
},
r_id:r_id, //Your custom option
cache: false,
success: function(val) {
console.log("r_id: " + this.r_id); //The custom option can be referenced with this.optProp
}
});
让我知道这是否对您有帮助,我们将为您解决
答案 1 :(得分:0)
您需要从服务器端函数返回一个具有id
属性的对象,这样您就可以在成功后像这样调用它:
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
var id = val.id; //gets the id attribute from the returned val Object
}
});
}