javascript - Codeigniter 如果插入数据再次返回 true 到 json ?这是可能的?

标签 javascript php json codeigniter

我使用 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/

相关文章:

javascript - 如何从 JavaScript 中的任何级别列表项元素访问顶级列表项元素?

php - while 循环只显示一个结果

java - JSON 响应字符串中包含自动添加的反斜杠

php - 转换 NSArray -> JSON -> NSData -> PHP 服务器 ->JSON 表示

javascript - .show().clone() html 不同于 .clone().show()

javascript - CSS 包含相对于 CSS 文件位置的图像

php - 尝试匹配两个数组中的值,如果存在匹配值则输出 true

php - 将文本转换为图像?

ruby-on-rails - 来自 JSON 文件的 Seed Rails SQLite 数据库

javascript - 如何在 Javascript 中将元素从禁用循环到启用