【问题标题】:Yii2: How to redirect with POST method?Yii2:如何使用 POST 方法重定向?
【发布时间】:2019-03-14 12:02:27
【问题描述】:

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

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

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

如何使用 POST 方法进行重定向?

【问题讨论】:

标签: php redirect post get yii2


【解决方案1】:

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

此方法在当前响应中添加一个“Location”标头。

您可以做的另一种选择是通过 ajax 调用 actionDelete 并从操作响应 successfailure 到 ajax 调用,您可以使用 @ 提交 id 987654327@。

例如考虑下面的代码,我们有一个按钮,我们在该按钮上绑定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;
}

【讨论】:

    【解决方案2】:

    我认为不可能,请参阅以下链接:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2013-10-04
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      相关资源
      最近更新 更多