Yii2,使用新数据部分渲染视图



yii2和PHP的新手,在这里遇到了休息。
基于这篇文章和这篇文章,我尝试重新创建 AJAX 调用。
现在,使用 Kartik SwitchInput 小部件,我至少尝试将值放入控制器,然后将其返回到索引页面上的另一个位置。

这是视图中的内容

...
<?= GridView::widget([
'dataProvider' => $customers,
'columns' => [
...
[
'label' => 'Status',
'format' => 'raw',
'attribute' => 'status',
'value' => function($models){
return SwitchInput::widget([
'name' => $models->id,
'value' => $models->status,
'pluginEvents' => [
'switchChange.bootstrapSwitch' => 'function(e) { 
$.ajax({
method: "POST",
url: "'.Url::to(['update-status']).'",
data: { "status": e.currentTarget.checked, "id": e.currentTarget.name },
error:function(res){
console.log(res.responseText);
}
})
console.log(`${e.currentTarget.checked}  ${e.currentTarget.name}`);
}'
]
...

下面是控制器:

class CustomerController extends Controller{
public function actionIndex(){
$customers = new ActiveDataProvider([
'query' => Customer::find()
]);
$models = $customers->getModels();
return $this->render('index', [ 
'customers' => $customers,
'models' => $models
]);
}
public function actionUpdateStatus(){
$status = Yii::$app->request->post('status');
$id = Yii::$app->request->post('id');
return $this->renderPartial('index', [
'status' => $status,
'id' => $id
]);
}
}

每当我拨动开关时,它都会返回 500 内部错误。Console.logging 它揭示了:$customers是未定义的。
据我所知,每当我进行 actionUpdateStatus 调用时,Yii 都会完全重新渲染视图,并尝试查找不在 UpdateStatus 中的$customers。
那么,如何将交换机数据分别返回到同一视图中呢?

我发布了您提到的答案之一,但我还没有在那里指定一件事,那就是重新加载网格视图,这不是那里的要求,但可以使用$.pjax来完成。

您需要注意的几件事

  • 根据您的要求,您不需要任何视图即可查看updateStatus操作。
  • 只需将一些状态代码返回到在 gridView 内用于切换输入的 ajax 调用,并刷新网格视图以加载新的更新状态。
  • 在 ajax 成功回调函数中,检查该状态代码是否正常,则应刷新网格视图,而不是使用呈现部分。
  • 而且您没有更新updateStatus中的任何内容? 您需要切换状态

因此,请将您的操作更改为以下内容

public function actionUpdateStatus()
{
try {
$status = Yii::$app->request->post('status');
$id = Yii::$app->request->post('id');
$model = Customer::findOne($id);
$model->status=$status;
if(!$model->save()){
throw new Exception(implode("n",yiihelpersArrayHelper::getColumn($model->errors,'0'));
}
return $this->asJson(['success' => true]);
} catch (Exception $e) {
return $this->asJson(['success' => false, 'message' => $e->getMessage()]);
}
}

确保已将 GridView 包装在 Pjax 开始和结束中,并向 Pjax 小组件添加id

<?php 
Pjax::begin(['id'=>'pjax-container']);
echo GridView::widget([
'dataProvider' => $customers,
'columns' => [
.......
]);
Pjax::end();
?>

以及您对以下内容的 ajax 调用

'switchChange.bootstrapSwitch' => 'function(e) {
$.ajax({
method: "POST",
url: "'.Url::to(['update-status']).'",
dataType:'json',
data: { "status": e.currentTarget.checked, "id": e.currentTarget.name },
success:function(data){
if(data.success){
$.pjax({container: "#pjax-container"});
}else{
console.log(data.message);
}
},
error:function(res){
console.log(res.responseText);
}
});
}'

最新更新