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’s Law.', 'Hofstadter’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">
“<?php echo $quote[0]?>”, <?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'=>'webmaster@example.com',
'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':'webmaster@example.com','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()
本文介绍如何使用 PHP 和 AJAX 实现动态更新页面内容,具体展示了如何通过 AJAX 请求从 PHP 服务器获取数据并在页面上实现动态交互,包括获取随机名言警句并提供“下一个名言”的按钮。
1299

被折叠的 条评论
为什么被折叠?



