简体   繁体   中英

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.

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:

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

  $(".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'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM