Sunday, 16 September 2012

Yii clientScript registerScript (example)

Function : Generate a piece of specific js script.


we have a button: 

<!--  {'func':'abc','par':'123'} is JSON format (key:value)! -->

<input type="button" onclick="myFunction({'func':'abc','par':'123'})" value='click me'/>

PHP ajax:

//Specify an ajax handler: 
//Controller : Ajax, Action: handler $ajaxUrl = $this->createUrl('ajax/handler'); 
$script = "function  myFunction (param){  
                    'type': 'GET',  
                    'url': '$ajaxUrl',  
                    'data': param,
//!!!!!if returned results are not json formatted, please delete dataType !!!!!!.
                    'dataType', 'json'  
                    'success': function(msg){
                               //success code put here!  

//register the script(generate the js).
// CClientScript::POS_END: gen js code after the html page is fully loaded. 
//the position of the JavaScript code. Valid values include the following:
      • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
      • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
      • CClientScript::POS_END : the script is inserted at the end of the body section.
      • CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
      • CClientScript::POS_READY : the script is inserted in the jQuery's ready function.

Yii::app()->clientScript->registerScript('updates', $script,        CClientScript::POS_END);

PHP controller:

class AjaxController extends Controller
public $defaultAction = 'Handler';
public function actionHandler()
    $func = $_GET['func'];
    $param = $_GET['par'];

For more info, about CClientScript :

帮自己宣传一下刚上线的网站 梦奇网;目前的提供的服务是 签证搜索 和 时间和日期。谢谢大家支持,SEO下!

No comments:

Post a Comment