您不能使用POST 方法重定向,因为它是Response::redirect() 的快捷方式,定义为
此方法在当前响应中添加一个“Location”标头。
您可以做的另一种选择是通过 ajax 调用 actionDelete 并从操作响应 success 或 failure 到 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;
}