如果条件在代码点火器的模型中不起作用


If condition not working in model of codeigniter

我正在尝试为我的网站实现一个"点赞"按钮。我使用的是Coddinger、Ajax和Jquery。当点击相似按钮时,数据应输入数据库,如果按下不同按钮,数据应从数据库中删除。但我在模型中遇到了一个问题,当我点击"赞"按钮时,数据并没有添加到数据库中。请帮我找到解决方案。

这是我的Jquery文件"likeitem.js"

function likeItem(postId)
{
    if ($("#likeItem_"+postId).text() == "Like") 
    {
        $("#likeItem_"+postId).html('Unlike');
        var purpose = "Like";
    }
    else 
    {
        $("#likeItem_"+postId).html('Like');
        var purpose = "UnLike";
    }
    $.ajax({
                type    : "POST",
                url     : "http://localhost/codeig_smarty/index.php/user/likeItem",
                data    : "postId=" + postId + "purpose=" + purpose,
                success : function() 
                {
                   
                }
            });
    return false;
}

这是我的模型"usermodel.php"

    public function itemLike()
    {
        $id         = $this->session->userdata('userID');
        $postId     = $this->input->post('postId');
        $purpose    = $this->input->post('purpose');
        
        if($purpose=="Like")
        {
//            echo 'test';
//            exit();
        $data   = array(
                        "userID"        => $id,
                        "postTextID"    => $postId,
                        );
        $this->db->insert('like', $data);    
        }
        else
        {
            echo 'hai';
        }
    }

这是我的视图文件"home.tpl"

 <li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>

这是我的控制器"user.php"

 public function likeItem()
    {
        $this->usermodel->itemLike();
    }
    

您在这里弄错了。您忘记放置&符号。试试这个代码。

data    : "postId=" + postId + "&purpose=" + purpose,

完整代码:若您想操作ajax返回的结果,您可以在成功块上做如下代码:

   $.ajax({
            type    : "POST",
            url     : "http://localhost/codeig_smarty/index.php/user/likeItem",
            data    : "postId=" + postId + "&purpose=" + purpose,
            success : function(data) 
            {
               // do seomthing here with data
               // console.log(data) --> to see data return or not
            }
        });