我使用 json 将数据发送到 Controller ,但如果数据成功插入数据库,我无法执行某些操作,
这个 if 语句在此 javascript 代码中不起作用? 我的意思是 .like-btn .html() 不起作用,但数据插入数据库?
My experience in Javascript between 0 and 10 :D
Using Codeigniter 3.0.3
这是我的 JavaScript
<script type="text/javascript">
$(document).ready(function() {
$(".like-btn").click(function(event) {
var liker_id = "<?php echo $this->session->userdata('id'); ?>";
var post_id = $(this).attr('post-id');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddLike'); ?>",
dataType: 'json',
data: {liker_id: liker_id, post_id: post_id},
success: function(res) {
if (res)
{
$('.like-btn[post-id = '+post_id+']').html('<span class="fa fa-check"></span> Liked');
}
}
});
});
});
</script>
这是我的 Controller
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
}
这是我的模型方法
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
return true;
}
}
最佳答案
只需在您的模型上进行以下更改:
将return
更改为echo
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
echo true;
}
}
关于javascript - Codeigniter 如果插入数据再次返回 true 到 json ?这是可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462588/