yii2控制器重定向功能中ajax请求错误

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

我在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
。事实证明,问题出在返回上,特别是重定向上。但这里可能出了什么问题,如何才能以不同的方式完成呢?

javascript php jquery ajax yii2
1个回答
0
投票

您可以使用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');
    }
});
}, 
© www.soinside.com 2019 - 2024. All rights reserved.