2016-10-18 53 views
0

我是新來的任何人都可以告訴我如何從索引中使用阿賈克斯jQuery的刪除選定的記錄得到檢查記錄ID這是選擇這是我的表單與AJAX腳本代碼沒有做任何動作,所以讓我知道我希望得到遏制多個記錄id在yii2

<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

您是否嘗試使用console.log(HotId)打印'HotId'數組?它是什麼顯示的 –

+0

是的我試過nitin,但它不工作我已經定義id也在gridview – sms

回答

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> 
+0

我越來越警覺,但沒有得到id – sms

+0

@sms:它現在工作嗎?如果是這樣,請接受答案,以便答案的人知道它,並且也會幫助其他人。 –

+0

還沒有還沒卡在這裏 – sms