2017-08-15 78 views
1

我有一個表像這樣的時候:路過​​值的一個控制器點擊一個按鈕

enter image description here

當我點擊刪除!按鈕,我想將角色ID傳遞給控制器​​。

在stackoverflow中尋找很多案件後。我剛剛成功地使用JS檢索角色ID。

這樣的代碼:

$(".deleteButton").click(function() { 
    var $row = $(this).closest("tr"); 
    var $text = $row.find("td:first-child").text(); 

    // Let's test it out 
    alert($text); 
}); 

但問題是,我不怎麼傳回的按鈕,這樣的話該按鈕可以將它傳遞給控制器​​。

有沒有簡單的方法將它傳遞給控制器​​?也許沒有先檢索角色ID,當點擊按鈕時,傳遞的值和控制器立即被調用?

這是我的代碼:

<table class="table" id="myTable"> 
    <thead class="text-primary"> 
     <th class="col-md-1">ID Role</th> 
     <th class="col-md-3">Role</th> 
     <th class="col-md-3">Jumlah Member</th> 
     <th></th> 
    </thead> 

    <tbody> 
    <?php 
     foreach($result as $row) { ?> 
     <tr> 
      <td><?php echo $row->id_role ?></td> 
      <td><?php echo $row->role ?></td> 
      <td><?php echo $row->jumlah ?></td> 
      <td> 
       <button type="button" class="btn btn-success btn-sm editButton">Edit!</button> 
       <button type="button" class="btn btn-danger btn-sm deleteButton">Delete!</button> 
      </td> 
     </tr> 
     <?php 
     } ?> 
    </tbody> 
</table> 
+0

在你的例子中,你的ID爲「text」 - 變量。您應該閱讀關於將變量傳遞給PHP而無需重新加載頁面的Ajax。 –

回答

1

你有使用JavaScript?如果不是,這是一種形式

<form action="path/to/your/controller" method="post"> 
<table class="table" id="myTable"> 
<!-- thead, etc --> 
<tbody> 
foreach($result as $row) : ?> 
<tr> 
    <td><?= $row->id_role ?></td> 
    <td><?= $row->role ?></td> 
    <td><?= $row->jumlah ?></td> 
    <td> 
    <button type="submit" name="edit" value="<?= htmlspecialchars($role->id_role) ?>" 
      class="btn btn-success btn-sm editButton">Edit!</button> 
    <button type="submit" name="delete" value="<?= htmlspecialchars($role->id_role) ?>" 
      class="btn btn-danger btn-sm deleteButton">Delete!</button> 
    </td> 
</tr> 
<?php endforeach ?> 
</tbody> 
</table> 
</form> 

一個簡單的任務,那麼你的控制器將接受或$_POST['edit']$_POST['delete']與角色ID作爲值。

如果您有興趣確保您的表單可能出現跨網站請求僞造攻擊,CodeIgniter has a built-in solution


否則,我只想在id_role屬性添加到該按鈕,如

<button type="button" class="btn btn-danger btn-sm deleteButton" value="<?= htmlspecialchars($role->id_role) ?>">Delete!</button> 

,並在你的JS

$('.deleteButton').on('click', function(e) { 
    var roleId = this.value 
    $.ajax({ 
    url: '/roles/' + roleId, // assuming a REST API 
    method: 'DELETE' 
    }).done(function() { 
    alert('Deleted role ' + roleId); 
    }) 
}) 
0

你的角色ID分配給另一個<td>這是一個稍微長一些,以獲得jQuery的id。你很容易得到點擊按鈕ID只是給一個像。

<button type="button" id="<?php echo $row->id_role ?>" class="btn btn-danger btn-sm deleteButton">Delete!</button> 

,然後就可以輕鬆搞定的具體行ID

$(".deleteButton").click(function() { 
    var $text= $(this).attr("id"); 

    alert($text); 
}); 

,然後你可以通過AJAX發送ID來控制。