繁体   English   中英

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

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

我在控制器中有Yii2 delete动作 ,我需要通过POST方法使用id变量重定向到index.php 这就是我使用GET方法的方法:

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

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

如何使用POST方法重定向?

您无法使用POST方法进行重定向,因为它是Response::redirect()的快捷方式,该方法定义为

此方法将“ Location”标头添加到当前响应。

您可以通过ajax调用actionDelete并响应从操作到ajax调用的successfailure ,您可以在其中使用$.post()提交id以实现所需的效果。

例如,考虑以下代码,在该代码上有一个按钮,该按钮上绑定了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']);

您的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;
}

我认为这是不可能的,请参见以下链接:

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

暂无
暂无

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

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