代码之家  ›  专栏  ›  技术社区  ›  Hector

控制器重定向函数中ajax请求的yii2错误

  •  0
  • Hector  · 技术社区  · 2 年前

    我在js中有这个请求

    requestSend: function(e)
    {
        let data = {
            request_id: e.target.dataset.request_id
        };
        $.ajax(
        {
            url: '/posts/save-changes',
            method: 'post',
            dataType: 'html',
            data: data,
            success: function()
            {
                console.log('success');
            },
            error: function()
            {
                console.log('error');
            }
        });
    },
    

    在php控制器中,一切看起来都是这样的

    public function actionSaveChanges()
        {
            $post = \Yii::$app->request->post();
            $this->Posts->updateFields($post['request_id'],$post);
    
            return \Yii::$app->controller->redirect('/posts');
        }
    

    当请求被执行时, error 来到我的控制台。在JSE本身中,我检查了所有数据,所有数据都显示正确,结果发现错误发生在php端。我在返回行之前使用了var_dump,在请求中我总是得到 success 。事实证明,问题在于返回,特别是重定向。但这里可能有什么问题,如何以不同的方式解决?

    0 回复  |  直到 2 年前
        1
  •  1
  •   Shukurullo Odilov    2 年前

    您可以使用javascript重定向页面。 在控制器中,返回如下响应:

    use yii\helpers\Url;
    
    public function actionSaveChanges()
    {
        $post = \Yii::$app->request->post();
        $this->Posts->updateFields($post['request_id'], $post);
        return $this->asJson([
            'url' => Url::to('/posts')
        ]);
    }
    

    在js中,按如下方式更改代码:

    requestSend: function(e){
    let data = {
        request_id: e.target.dataset.request_id
    };
    $.ajax(
    {
        url: '/posts/save-changes',
        method: 'post',
        dataType: 'html',
        data: data,
        success: function(result)
        {
        window.location.href = result.url
        },
        error: function()
        {
            console.log('error');
        }
    });
    },