How to make ajax call in yii2?

2019-03-13 13:41发布

问题:

In yii version 1.14 we used

CHtml::ajaxlink

for ajax call what about in yii2?

回答1:

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;",
                ]);


回答2:

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


回答3:

$.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



回答4:

<?=yii\helpers\Url::toRoute("site/signup")?>


标签: php yii2