美好的一天
我有一个显示公告的页面。
我想在每一分钟检查公告是否有任何变化
如果有任何更改,我应该更新页面的内容
因此,我需要将旧的公告发送回控制器进行检查
但我的问题是我不知道如何将整个对象从数据库发送回控制器。
(我只能发送普通的单一数据类型,如string,int等)
以下是我的代码的概述
先感谢您。
我的观点(php)
<div class="row " id="tabapp_news">
<div class="container">
<div class='tickercontainer'>
<div class='mask'>
<ul id="telop">
<?php
foreach ($announces as $announce) {
echo '<li>' . $announce->comment . '</li>';
}
?>
</ul>
</div>
</div>
</div>
</div>
控制器
public function actionIndex()
{
$announces = [];
$desk_id = Yii::$app->request->get(DESK_KEYWORD);
if (!empty($desk_id)) {
$desk = Desk::find()
->where((['id' => $desk_id]))
->one();
if ($desk) {
$announces = Announce::getOpeningAnnouncesByDesk($desk->id);
}
}
return $this->render('announce', [
'announces' => $announces,
'desk' => $desk,
]);
}
public function actionCheckNewAnnounce()
{
$announces = Yii::$app->request->post('announces');;
$desk_id = Yii::$app->request->get(DESK_KEYWORD);
if (!empty($desk_id)) {
$desk = Desk::find()
->where((['id' => $desk_id]))
->one();
if ($desk) {
$new_announces = Announce::getOpeningAnnouncesByDesk($desk->id);
if (array_diff($new_announces, $announces)) {
return $this->render('announces', [
'announces' => $new_announces,
'desk' => $desk,
]);
}
}
}
return "";
}
我的javascript / ajax
var interval = setInterval(function(){
$.ajax({
url: '/check-new-single',
dataType: 'html',
data: {announces: $("#info").data('announces')},
method: 'post',
success: function(response) {
if (response != "") {
$('#telop').empty();
$('#telop').append(response);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("ajax communication failure.");
}
});
}, 60000);
答案 0 :(得分:0)
您的观点(index.php)
<div class="row " id="tabapp_news">
<div class="container">
<div class='tickercontainer'>
<div class='mask'>
<ul id="telop">
<?php
echo $this->render('annnounce',['announces' => $announces])
?>
</ul>
</div>
</div>
查看(announce.php)
<?php
foreach ($announces as $announce) {
echo '<li>' . $announce->comment . '</li>';
}
?>
<强> JS 强>
var interval = setInterval(function(){
$.ajax({
url: '/check-new-announce',
dataType: 'html',
data: {announces: $("#info").data('announces')},
method: 'post',
success: function(response) {
if (response != "") {
$('#telop').html(response);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("ajax communication failure.");
}
});
}, 60000);
控制器操作
更改渲染以渲染Ajax
public function actionCheckNewAnnounce()
{
$announces = Yii::$app->request->post('announces');;
$desk_id = Yii::$app->request->get(DESK_KEYWORD);
if (!empty($desk_id)) {
$desk = Desk::find()
->where((['id' => $desk_id]))
->one();
if ($desk) {
$new_announces = Announce::getOpeningAnnouncesByDesk($desk->id);
if (array_diff($new_announces, $announces)) {
return $this->renderAjax('announce', [
'announces' => $new_announces,
]);
}
}
}
return "";
}