jQuery:使用AJAX调用更改按钮类

我正在构建一个Like / Different系统,我有一个类似于类的按钮,如果我点击它将数据插入数据库,并且类更改为不同。

并且不像假设拉另一个ajax调用什么删除实际像但它不工作,当类更改它预先形成像类假设做什么,它只有在我刷新页面时才有效。

PHP代码

<?php $like = ''; foreach ($user->likes as $likes) { if($likes['liked_by'] == Session::get('sentry_user')) { $like = ''; break 1; } } echo $like; ?>

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(' Unlike'); } }, complete: function() { $(this).removeClass('disabled'); } }); }); $('button.unlike').bind('click', function(){ var likeId = $(this).data('like'); alert('you are about to unlike'); }) 

刚刚做了一个不同的警报示例来测试它,因为我用它做了ajax调用。

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

我在我的应用程序上做了类似的事情,我使用了这个逻辑:

HTML:

  

JS:

  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调用,你将拥有更少的代码

你也可以使用$(selector).toggleClass(); 像这样:

jQuery的:

 $('button.like,button.unlike').on('click',function(){ $.ajax( ... $(this).toggleClass('like unlike'); ); }) 

这是一个jsbin

您可以使用像http://phery-php-ajax.net这样的库来使您能够保持代码干燥,并且可以重用代码而无需重新绑定点击事件:这将适用于通过添加的所有按钮ajax,可以在任何地方重复使用

data-remote是远程函数的名称,在本例中是action。 它使用事件委派,因此无需手动将click事件绑定到按钮

 
$user->id, 'perform' => 'like')).'"> Like '; foreach ($user->likes as $likes) { if($likes['liked_by'] == Session::get('sentry_user')) { $like = ''; break 1; } } echo $like; ?>

你喜欢/不像回调

 // in your profile/like function action($data){ $r = new PheryResponse; // $data['id'] got the ID of the like if ($data['perform'] === 'like'){ $r ->this() ->removeClass('like') ->addClass('unlike') ->phery('set_args', array('id' => $data['id'], 'perform' => 'unlike')) ->html(' Unlike'); // exchange the data } elseif ($data['perform'] === 'unlike'){ $r ->this() ->removeClass('unlike') ->addClass('like') ->phery('set_args', array('id' => $data['id'], 'perform' => 'like')) ->html(' Like'); // exchange the data } return $r; } Phery::instance()->set(array( 'action' => 'action' ))->process();