How to make ajax call in yii2?

2019-03-13 13:13发布

In yii version 1.14 we used

CHtml::ajaxlink

for ajax call what about in yii2?

标签: php yii2
4条回答
倾城 Initia
2楼-- · 2019-03-13 13:27
$.get( "' . Url::toRoute('controller/action') . '", { item: $("#idoffield").val()} ) /* to send the parameter to controller*/
                        .done(function( data )
                            {
                                 $( "#lists" ).html( data );
                                    }) 

and give lists id for div

<div id="lists"></div>

for more visit https://youtu.be/it5oNLDNU44

查看更多
甜甜的少女心
3楼-- · 2019-03-13 13:40

You can make an ajax link like

 Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
    'onclick'=>"$('#close').dialog('open');//for jui dialog in my page
     $.ajax({
    type     :'POST',
    cache    : false,
    url  : 'controller/action',
    success  : function(response) {
        $('#close').html(response);
    }
    });return false;",
                ]);
查看更多
乱世女痞
4楼-- · 2019-03-13 13:42

From: http://www.yiiframework.com/wiki/665/overcoming-removal-of-client-helpers-e-g-ajaxlink-and-clientscript-in-yii-2-0/

You can easily create and combine all such client helpers for your need into separate JS files. Use the new AssetBundle and AssetManager functionality with the View object in Yii2, to manage these assets and how they are loaded.

Alternatively, inline assets (JS/CSS) can be registered at runtime from within the View. For example you can clearly simulate the ajaxLink feature using a inline javascript. Its however recommended if you can merge where possible, client code (JS/CSS) into separate JS/CSS files and loaded through the AssetBundle. Note there is no more need of a CClientScript anymore:

$script = <<< JS
$('#el').on('click', function(e) {
    $.ajax({
       url: '/path/to/action',
       data: {id: '<id>', 'other': '<other>'},
       success: function(data) {
           // process data
       }
    });
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default), 
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
查看更多
女痞
5楼-- · 2019-03-13 13:43
<?=yii\helpers\Url::toRoute("site/signup")?>
查看更多
登录 后发表回答