Sunday 16 September 2012

Yii clientScript registerScript (example)

Function : Generate a piece of specific js script.

Example:

HTML: 
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:


<?php 
//Specify an ajax handler: 
//Controller : Ajax, Action: handler $ajaxUrl = $this->createUrl('ajax/handler'); 
$script = "function  myFunction (param){  
           $.ajax({  
                    '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:

<?php 
class AjaxController extends Controller
{
public $defaultAction = 'Handler';
public function actionHandler()
{
    $func = $_GET['func'];
    $param = $_GET['par'];
}
}
?>

For more info, about CClientScript : http://www.yiiframework.com/doc/api/1.1/CClientScript

http://daxue.menggy.com






No comments:

Post a Comment