[英]How to load article without page reloading in Yii & Ajax
I have an viewing articles from databases and every article view with hole page load. 我从数据库中查看文章,并且每个文章视图都带有漏洞页面加载。 So I would load articles without page reloading, I think this is possible using Ajax but I'm not so strong about it. 因此,我将加载文章而无需重新加载页面,我认为使用Ajax可以实现此目的,但我对此并不坚决。
This is my initial concept like below: 这是我的初始概念,如下所示:
Layout: 布局:
CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
)
);
// This showing articles name & link
View: 视图:
<?php
echo $model->article_body;
?>
<script>
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: ('articles/view'),
success: function(data){
document.getElementById('articles').innerHTML = data;
},
error: function(){
alert('Somthing wrong');
}
});
</script>
Controller: 控制器:
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
Does someone can help me? 有人可以帮我吗? Thanks 谢谢
You must return json: 您必须返回json:
public function actionView($id)
{
$model=$this->loadModel($id);
...
echo CJSON::encode(
array(
'status' => 'success',
'content' => $this->renderPartial('view',
array(
'model' => $model,
),
true,
true
),
)
);
}
if i understood you correctly, 如果我正确理解你,
in your view file something like this. 在您的视图文件中是这样的。
echo CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
),array('class'=>'youclassnamehere')
);
echo '<div id="yourDivId"></div>';
in javascript your code should be something like eg 在JavaScript中,您的代码应类似于例如
$(".youclassnamehere").click(function(){
$.ajax({
type:'POST',
url:$(this).attr('href'),
success:function(data){
$("#yourDivId").html(data);
}
error:function(data){
alert('Error occured please try again later..');
}
}),
return false;//this will not redirect your page
});
in controller action your code like eg 在控制器动作中,您的代码例如
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
hope this will help you 希望这个能对您有所帮助
I reach solution from above answer but I newly add like below: 我从上面的答案中获得解决方案,但我新添加了如下内容:
array(
'onclick'=>'javascript:return false'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.