yii2从视图和调试过程调用控制器操作

问题描述 投票:0回答:1

在数据网格视图中,我有一个textinput字段,如果字段更新,我想调用控制器函数。因此我在脚本中加入了一个脚本并准备了一个控制器功能。

$this->registerJs(
    "$('#product_qty').on('click', function() { 
        alert('Button clicked!'); 
        $.ajax({
            url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',
            type: 'post',
            data: {
                 id: '5' , 
                 _csrf : '" . Yii::$app->request->getCsrfToken() . "'
             },
            success: function (data) {
                console.log(data.search);
                },
            });
    });",
    \yii\web\View::POS_READY,
    'my-button-handler'
);

将调用警报功能并显示“单击按钮”。然后什么都没发生

Suppliers_orderController函数的控制器是:

public function actionChangequantity(){

        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();
            $id = $data['id'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'search' => $id,
        ];
}

此外,我想用phpstorm和xdebug跟踪活动,但调试过程不会停在控制器的第一个断点处。缺少什么,或者我的JS功能错了?

javascript ajax debugging controller yii2
1个回答
1
投票

最重要的是,在Yii2你有\yii\helpers\Url::base();得到baseurl而不是Yii::$app->request->baseUrl;这是在没有baseUrl的控制台中错误的网址打印的原因,所以改变你的线

url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',

以下

url: '".\yii\helpers\Url::base(). '/suppliers_orders/changequantity' . "',

其次,如果您使用localhost路径而不是虚拟主机用于frontendbackend以及访问controller/action,您必须使用index.php以及web之后的路径,如下所示

http://localhost/myproject/backend/web/index.php/suppliers_orders/changequantity

© www.soinside.com 2019 - 2024. All rights reserved.