我是新来的,任何人都可以告诉我如何从索引中获取已检查记录ID以使用 Ajax 和 Jquery 删除所选记录这是我的表单和ajax脚本用于选择此代码不执行任何操作,请告诉我
<div class="usermaster-model-index">
<input type="button" class="btn btn-info pull-right" value="Delete Multiple" id="MyButton" >
<h1><?= Html::encode($this->title) ?></h1>
<?php
?>
<p>
<?= Html::a('Create Usermaster Model', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'class' => ActionColumn::className(),
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_fname',
'user_id',
'user_lname',
'user_mobile',
['class' => 'yii\grid\ActionColumn'],
[ 'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => ["attribute" => 'user_id'],
],
],
]);
?>
</div>
<script>
$(document).ready(function () {
$('#MyButton').click(function () {
alert('hello');
var HotId = $('#user_id').yiiGridView('getSelectedRows');
$.ajax({
type: 'POST',
cache: false,
url: Url::toRoute('usermaster/MultipleDelete'),
data: {user_id: HotId},
success: function () {
$(this).closest('tr').remove();
}
});
});
});
</script>
这里我的控制器动作删除多个数据函数以获取所选的id并删除
public function actionMultipleDelete()
{
$data = Yii::$app->request->post('user_id');
foreach ($data as $key => $value)
{
$sql = "DELETE FROM usermaster WHERE user_id = $value";
$query = Yii::$app->db->createCommand($sql)->execute();
}
return $this->redirect(['index']);
}
答案 0 :(得分:1)
在您的gridview中添加id
选项
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'id'=> your-id //set your id here and use this is in jquery
//'class' => ActionColumn::className(),
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_fname',
'user_id',
'user_lname',
'user_mobile',
['class' => 'yii\grid\ActionColumn'],
[ 'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => ["attribute" => 'user_id'],
],
],
]);
并在Jquery中用您的新ID替换user_id
,如下所示。
<script>
$(document).ready(function () {
$('#MyButton').click(function () {
alert('hello');
var HotId = $('#your-id').yiiGridView('getSelectedRows'); // modify this line
$.ajax({
type: 'POST',
cache: false,
url: Url::toRoute('usermaster/MultipleDelete'),
data: {user_id: HotId},
success: function () {
$(this).closest('tr').remove();
}
});
});
});
</script>