簡體   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