YII AJAX registerScript

1.YII封装的CHtml::ajaxLink,QuoteController.php

<?php
class QuoteController extends Controller
{
	private $quotes = array(
		array('Walking on water and developing software from a specification are easy if both are frozen.', 'Edward V Berard'),
		array('It always takes longer than you expect, even when you take into account Hofstadter&rsquo;s Law.', 'Hofstadter&rsquo;sLaw'),
		array('Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.','Rick Osborn'),
		array('I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone.', 'Bjarne Stroustrup'),
		array('Java is to JavaScript what Car is to Carpet.', 'Chris Heilmann'),
	);
	private function getRandomQuote()
	{
		return $this->quotes[array_rand($this->quotes, 1)];
	}
	function actionIndex()
	{
		$this->render('index', array(
		'quote' => $this->getRandomQuote()
		));
	}
	function actionGetQuote()
	{
		$this->renderPartial('_quote', array(
		'quote' => $this->getRandomQuote(),
		));
	}
}

view/index.php

<h2>Quote of the day</h2>
<div id="quote-of-the-day">
&ldquo;<?php echo $quote[0]?>&rdquo;, <?php echo $quote[1]?>
</div>
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php echo CHtml::ajaxLink('Next quote', array('getQuote'),
array('update' => '#quote-of-the-day'))?>

 ajaxLink($text,$url ,$ajaxOptions=array(),$htmlOptions=array())

$text 链接内容

以下是调试.也可以用常用的jQuery.ajax

<?php echo CHtml::ajaxLink('Next quote', array('getQuote'),
array('success' => 'js:function(data){
alert(data);
}'))?>

 

2.将php数据转化成javascript数据

protected/config/main.php:

'params'=>array(
	// this is used in contact page
	'adminEmail'=>'[email protected]',
	'alert' => array(
		'enabled' => true,
		'message' => 'Hello there!',
	),
),

protected/controllers/AlertController.php

<?php
class AlertController extends Controller
{
	function actionIndex()
	{
		$config = CJavaScript::encode(Yii::app()->params->toArray());
		//$config:{'adminEmail':'[email protected]','alert':{'enabled':true,'message':'Hello there!'}}
		Yii::app()->clientScript->registerScript('appConfig', "var config = ".$config.";",CClientScript::POS_HEAD);
		$this->render('index');
	}
}

registerScript第二个参数是显示js代码。

<?php
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$.fn.yiiGridView.update('project-grid', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

protected/views/alert/index.php

<script>
if(config && config.alert && config.alert.enabled &&
config.alert.message){
alert(config.alert.message);
}
</script>

CJSON::encode()=CJavaScript::encode   生成json格式
CJSON::decode()

 

 

你可能感兴趣的:(params,registerScript)