2017-04-03 89 views
0

我需要動態分配一個元素上的ID做一個POST請求,然後添加一個類到另一個元素。我真的是JS的noob,所以我認爲我弄得一團糟..阿賈克斯 - 動態創建一個按鈕發佈請求

基本上,我有一個創建行的forEach循環的jsp頁面。在最後我有一個鏈接點擊哪個發送POST請求。根據請求的結果(布爾型T/F),我需要在元素上應用一個類。

問題是如何創建一個動態ID傳遞給腳本,以及如何選擇添加基於POST結果的類。

我的JSP有這個forEach循環

<c:forEach items="${notifications }" var="notification"> 
    <tr id="${notification.notificationId }"> 
     <td class="actions pull-right"><a href="#"> <i class="fa fa-gear"></i></a></td> 
    </tr> 
</c:forEach> 

劇本

$(document).ready(function(){ 
    $("#${notification.notificationId").closest('a').click(function(){ 
      $.ajax({ 
       type: 'POST', 
       url: '/${notification.notificationId}', 
       dataType: 'text', 
       success: function (text) { 
        $("#${notification.notificationId"}).addClass("font-bold"); 
        alert(text); 
       }) 
     }) 
    }) 

顯然這是行不通的,因爲$("#${notification.notificationId"})這不是正確的(我不知道該腳本的其餘部分作品太...

+0

相反,你可以做的是分配一個數據屬性的TR。 IE:data-notification-id =「$ {notification.notificationId}」。還要爲每個可點擊的tr添加一個類。然後在jquery中使用類($'。tr-class')。on('click',function(e){var id = $(this).data('notification-id').... then其餘的東西...}) – Budhead2004

回答

0

首先,你需要獲得點擊鏈接行容器。你選擇被點擊的元素,並獲得它的父級,直到你的權利連續ainer。 以上是你可能需要做的一個例子。

$(document).ready(function() { 

    $("tr > td > a").on("click", function (e) { 
     // This will prevent your link to navigate to "#" 
     e.preventDefault(); 

     // This is the container row of the link that was clicked 
     var $tr = $(this).parent().parent(); 

     // The ajax request 
     $.ajax({ 
     type: "post", 
     url: "/" + $tr.attr("id"), // This will take the ID of the row container. Eg: ID=1 it will navigate to "/1" 
     dataType: "text", 
     success: function (response) { 
      // I presume that you response will be either "true" or "false" like you mention 
      // So, if the response is "true", then we add the class to the row container 
      if (response == "true") { 
      $tr.addClass("font-bold"); 
      } 

     }); 

     }); 

    }); 

}); 

祝你好運!

+0

謝謝!有效! – besmart