gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:13:00 25 4
gpt4 key购买 nike

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

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

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

如何使用 POST 方法重定向?

最佳答案

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

This method adds a "Location" header to the current response.

您可以选择通过 ajax 调用 actionDelete 并从操作中响应 successfailure 来达到预期效果到 ajax 调用,您可以在其中使用 $.post() 提交 id

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

关于php - Yii2:如何使用 POST 方法重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com