简体   繁体   中英

yii2: Dynamically call widget

Lets imagine that I have some widget: Widget1;

I call this widget in view file.

<?= Widget1::widget() ?>

When you click on some element, a new instance of the widget should be called and execute js scripts of this widget. I can not realize the script execution after ajax call;

Create an ajax call to a controller action where you will instantiate your widget and/or call it's javascript returning functions. Like this:

//@app/widget/Widget1
class Widget1 extends \yii\base\Widget
{
    public function run()
    {
        echo new JsExpression('function(){ alert("hello,world") }');
    }
}

//@app/controllers/SomeController
public function actionSomeaction()
{
    return Widget1::widget();
}

And then call that from your ajax function that's handling onClick event(example in jquery):

<script>
    $.post('/some/someaction',function(response){
        response();
    });
</script>

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