2010-03-02 78 views
0

我在登錄的用戶可以使用的頁面上有一個訂閱鏈接。jQuery訂閱鏈接切換

切換頁面上的鏈接是沒有問題,因爲我可以做一個。員額和回聲出PHP返回什麼

if ($subscription == true) { 
    echo 'Subscribed'; 
} else { 
    echo 'Click to subscribe'; 
} 

但是,我是什麼錯誤,我必須寫同一塊代碼在我的模板文件中。然而,我可以在頁面加載時立即爲此做出ajax調用。

這樣做的最好方法是什麼?

回答

0

好吧,我決定用PHP修復它。現在,當你點擊頁面它呼籲:

http://url/module/controller/check/id/ $ ID /對象/ $ OBJECT_NAME

和ajax'd到我的股利。然後,如果點擊它去,並把返回值在HTML

http://url/module/controller/toggle/id/ $ ID /對象/ $ OBJECT_NAME

類:

<?php 


class User_SubscriptionController extends Zend_Controller_Action { 


function init() { 
    $contextSwitch = $this->_helper->getHelper('ForceContext'); 
    $userSess  = new Zend_Session_Namespace('User'); 
    $this->user  = $userSess->model; 

    $this->id   = $this->_getParam('id'); 
    $this->object_name = $this->_getParam('object'); 

    if (empty($this->id) || empty($this->object_name)) { 
     throw new exception('Id and Object name must be passed'); 
    } 

} 


public function checkAction() { 

    $subscription = Eurocreme_Baseclass::load_by_fields(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription'), 1); 

    if (is_object($subscription)) { 
     echo 'Click To Un-Susbscribe'; 
    } else { 
     echo 'Click To Subscribe'; 
    } 
    exit; 
} 


public function toggleAction() { 

    $subscription = Eurocreme_Baseclass::load_by_fields(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription'), 1); 

    if (is_object($subscription)) { 
     $subscription->delete(); 
    } else { 
     $subscription = Eurocreme_Baseclass::create(array('object_name' => $this->object_name, 'object_id' => $this->id, 'user_id' => $this->user->id, 'table_name' => 'Subscription', 'frequency' => 1)); 
    } 

    $this->checkAction(); 
} 

}

和視圖代碼:

<?php $this->headScript()->captureStart(); ?> 
$('document').ready(function() { 

    $.get('/user/subscription/check/id/<?php echo $this->object->id; ?>/object/Movie', function(data) { 
     $('#subscription_link').html(data); 
    }); 

    $("#subscription_link").click(function(){ 
     $.get('/user/subscription/toggle/id/<?php echo $this->object->id; ?>/object/Movie', function(data) { 
      $('#subscription_link').html(data); 
     }); 
     return true; 
    }); 


}); 
<?php $this->headScript()->captureEnd(); ?>