简体   繁体   English

Yii2:如何使用POST方法重定向?

[英]Yii2: How to redirect with POST method?

I have the Yii2 delete action in a controller and I need to redirect to index.php with the id variable by POST method. 我在控制器中有Yii2 delete动作 ,我需要通过POST方法使用id变量重定向到index.php This is how I do it with GET method: 这就是我使用GET方法的方法:

public function actionDelete($id)
{
    $this->findModel($id)->delete();

    return $this->redirect(['index?id=' . $id]);
}

How can I redirect using the POST method? 如何使用POST方法重定向?

You cannot redirect using the POST method as it is a shortcut to Response::redirect() which is defined as 您无法使用POST方法进行重定向,因为它是Response::redirect()的快捷方式,该方法定义为

This method adds a "Location" header to the current response. 此方法将“ Location”标头添加到当前响应。

What you can do alternatively to achieve the desired effect is to call the actionDelete via ajax and response a success or failure from the action to the ajax call where you can submit the id using the $.post() . 您可以通过ajax调用actionDelete并响应从操作到ajax调用的successfailure ,您可以在其中使用$.post()提交id以实现所需的效果。

For example consider the following code where we have a button on which we bind the click event and get the id of the record that we need to delete, it can either be inside a hidden field, we send the request to the actionDelete and if all is ok we submit the id using $.post() . 例如,考虑以下代码,在该代码上有一个按钮,该按钮上绑定了click事件并获取需要删除的记录的ID,它可以在隐藏字段内,然后将请求发送到actionDelete ,如果所有可以,我们使用$.post()提交ID。

$js = <<< JS

$("#delete").on('click',function(){
    var id = $("#record_id").val();
    $.ajax({
        url:'/controller/action',
        method:'post',
        data:{id:id},
        success:function(data){
            if(data.success){
                $.post('/controller/action',{id:data.id});
            }else{
                alert(response.message);
            }
        }
    });
});
JS;
$this->registerJs($js,\yii\web\View::POS_READY);
echo Html::hiddenInput('record_id', 1, ['id'=>'record_id']);
echo Html::button('Delete',['id'=>'delete']);

Your actiondelete() should look like below 您的actiondelete()应该如下所示

public function actionDelete(){

    $response = ['success'=>false];

    $id = Yii::$app->request->post('id');

    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    try{
        $this->findModel($id)->delete();
        $response['success'] = true;
        $response['id'] = $id;
    }catch(\Exception $e){
        $response['message'] = $e->getMessage();
    }
    return $response;
}

I don't think it is possible, see below link: 我认为这是不可能的,请参见以下链接:

https://forum.yiiframework.com/t/redirect-with-post/36684/2 https://forum.yiiframework.com/t/redirect-with-post/36684/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM