$toggle = $model->is_favourite? "false": "true";
$actionUrl = Yii::app()->createUrl('user/favoritePage', array(
'playerId'=>$player->id, 'pageId'=>$page->id
));
//render input type=submit with id=favourite-button
echo CHtml::ajaxSubmitButton(
($model->is_favourite? 'Favourite' : 'Un-Favourite'), //label button
$actionUrl,
array(
'data' => 'js:{bool: $("#favourite-button").attr("toggle")}', //get current status of button (favourite or not) as param to post
'success'=>'js:function(data){
//ajax success, update label and status of button for next time
data = $.parseJSON(data);
$("#favourite-button").val(data["label"]);
$("#favourite-button").attr("toggle", data["toggle"]);
}'
),
array(
'id' => 'favourite-button', // set id for button
'toggle' => $toggle // set attribute to hold favourite status, or you can set it on hidden field instead and then update the selector on ajax success
)
);
在控制器用户
public function actionfavoritePage(){
if( Yii::app()->request->isAjaxRequest(){ // this check is not necessary if you write this function just for ajax call only
$playerId- = $_GET['playerId']; // get query string
$pageId- = $_GET['pageId']; // get query string
$bool = $_POST['bool']; // get status true OR false
//do your stuff to save status here
...
//then return result as json
echo json_encode(array('label' => '[your new button label]', 'toggle'=>$bool?'false':'true'));
exit();
})
}