jQuery的:改变类按钮与AJAX调用按钮、jQuery、AJAX

2023-09-11 00:34:54 作者:莫言离殇。

我建立了一个类似/不同的系统,我有一个按钮有什么一类像,如果我点击它的数据插入到数据库中,类改为不同。

I am building up a Like/Unlike system, I have a button what has a class like, if i click it data is inserted in the database, and the class is changed to unlike.

和不同假设去拉另一个Ajax调用什么消除实际像,但其没有工作,上课的时候​​改成了preforms什么样的班级想这样做,它只能如果我刷新页面。

And unlike suppose to pull another ajax call what removes the actual like but its not working, when the class changed it preforms what like class suppose to do, and it only works if i refresh the page.

PHP code

<div class="btn-group pull-right">
<?php
    $like = '<button class="btn btn-primary btn-small like" data-like="'.$user->id.'">
        <i class="icon-thumbs-up icon-white"></i> Like
    </button>';  
    foreach ($user->likes as $likes) {
        if($likes['liked_by'] == Session::get('sentry_user')) {
          $like = '<button class="btn btn-primary btn-small unlike" data-like="'.$user->id.'">
            <i class="icon-thumbs-down icon-white"></i> Unlike
            </button>'; 
            break 1;
         }
    }
    echo $like; 
 ?>
</div>

jQuery的

jquery

$('button.like').bind('click', function(){
    var likeId = $(this).data('like');
    $.ajax({
        url: siteUrl + 'profile/like',
        type: "post",
        data: {user_id: likeId},
        dataType: "json",
        context: this,
        beforeSend: function()
        {
            $(this).addClass('disabled');
        },
        success: function(data)
        {
            if(data.status == "like") {
                $(this).removeClass('like')
                .addClass('unlike')
                .append()
                .html('<i class="icon-thumbs-down icon-white"></i> Unlike');
            }
        },
        complete: function()
        {
            $(this).removeClass('disabled');
        }
    });

});

$('button.unlike').bind('click', function(){
    var likeId = $(this).data('like');
    alert('you are about to unlike');


})

刚做的不同的警报的例子来测试它befoe我做的AJAX调用它。

just made the unlike alert for an example to test it befoe I make the ajax call with it.

所以,云有人给我一个提示?

So cloud someone give me a hint?

推荐答案

我已经做了类似的事情在我的应用程序,我用这样的逻辑:

i've done something similar on my app, i used this logic:

HTML:

<a class="like" onclick="like($(this))"></a>

记者:

    function like(_element){

    if($(_element).hasClass('unlike')){

$.ajax(); //do unlike
    $(_element).removeClass('unlike'); // this goes inside the success:function(){} of the ajax call

}else{

     $.ajax(); //do like    
     $(_element).addClass('unlike'); // this goes inside the success:function(){} of the ajax call

}

    }

你也可以重构这个例子只使用1 Ajax调用,您将有较少code

also you can refactoring this example for using just 1 ajax call, you will have less code