JSON is a very simple, compact, and therefore widely used format for AJAX application's data exchange. Yii has a few handy ways to work with it. Therefore, let's create a simple application that will show a news list and update it every two seconds.
yiic webapp
tool.news
with at least id
, created_on
, and title
fields, as shown in the following code:CREATE TABLE `news` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`created_on` int(11) unsigned NOT NULL,`title` varchar(255) NOT NULL,PRIMARY KEY (`id`))
News
model using Gii.protected/controllers/NewsController.php
as follows:<?php class NewsController extends Controller { public function filters() { return array( 'ajaxOnly + data', ); } public function actionIndex() { $this->render('index'), } public function actionData() { $criteria = new CDbCriteria(); $criteria->order = 'created_on DESC'; $criteria->limit = 10; $news = News::model()->findAll($criteria); echo CJSON::encode($news); } public function actionAddRandomNews() { $news = new News(); $news->title = "Item #".rand(1, 10000); $news->created_on = time(); $news->save(); echo "OK"; } }
protected/views/news/index.php
as follows:<div class="news-list"> Loading… </div> <?php Yii::app()->clientScript->registerCoreScript("jquery")?> <script type="text/javascript"> jQuery(function($) { var newsList = $('.news-list'), function updateNews(){ newsList.html("Loading…"); $.ajax({ url: "<?php echo $this->createUrl('data')?>", dataType: 'json', cache: false, success: function(data) { var out = "<ol>"; $(data).each(function(){ out+="<li>"+this.title+"</li>"; }); out += "</ol>"; newsList.html(out); } }); } updateNews(); setInterval(function(){ updateNews() }, 2000); }); </script>
index
action of the news controller and try to add a few records into the news
database table by running the addRandomNews
action. Do not refresh the index
page. News added will appear on the index
page once every two seconds, as shown in the following screenshot:The index
action does nothing special, it simply renders a view that includes a div
container and some JavaScript code. As we are using jQuery, we need to ensure that it is included properly:
<?php Yii::app()->clientScript->registerCoreScript("jquery")?>
Then, we define a function named updateNews
and run it every 2,000 milliseconds using the core JavaScript setInterval
function. In updateNews
, we make an AJAX request to the data
action of the same controller to process the JSON response and replace the current content of the placeholder div
with formatted data.
In actionData
, we get the latest news and convert them to JSON format by passing the result to CJSON::encode
.
For further information, refer to the following URLs:
3.133.144.197