2013-10-17 21 views
1

我有一個表格,顯示了我的案例中的「目擊」列表,每個特定的列可以更新爲值顯示在字段等。每個單獨的行上有一個更新按鈕當我完成更新該特定行時,我想單擊它。這是我forEach循環顯示的所有條目:用ajax更新每行的輸入

<c:forEach var="mySightings" items="${mySightings}">  
      <tr> 
       <td><input name="id" class="data sighting_id" disabled value="${mySightings.id}"/></td> 
       <td><input name="total_pests" type="number" value="${mySightings.total_pests}"/></td> 
       <td><input name="date" type="date" value="${mySightings.date}"/></td> 
       <td><input name="username" disabled value="${mySightings.username}"/></td> 
       <td><textarea name="information">${mySightings.information}</textarea></td> 
       <td> 
        <button class="update_sighting btn btn-success">Update</button> 
       </td> 
       <td> 
        <button class="delete_sighting btn btn-danger" value="${mySightings.id}">Delete</button> 
       </td> 
      </tr>  
</c:forEach> 

這是我的Ajax功能,我認爲這是絕對錯誤:

$(".update_sighting").click(function(){ 
    $.ajax({ 
     type: "POST", 
     url: "${pageContext.request.contextPath}/updateSighting", 
     data: $(this).serialize(), 
     success: function(response) { 
      $("#alert").show(); 
      alert("Submitted"); 
      $(".errormsg").hide(); 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert("Status: " + textStatus); alert("Error: " + errorThrown); 
     } 
    }); 
}); 

我需要改變某些事情了我的Ajax代碼?我不知道接下來該做什麼? 我的控制器,該控制器處理請求:

@RequestMapping(value = "/updateSighting", method = RequestMethod.POST) 
public @ResponseBody String updateUser(Sighting sighting, Model model) { 
    sightingsService.updateSighting(sighting); 
    List<Sighting> sightings = sightingsService.getAllSightings(); 
    model.addAttribute("sightings", sightings); 
    return "allSightings"; 
} 

請幫幫忙,謝謝

回答

1

的問題是與序列化的數據。您在button元素上調用它,而不是form,但即使如此,它也會將整個表單串行化,而不僅僅是單擊的行。所以你需要建立對象以手動進行序列化:

$(".update_sighting").click(function(){ 
    var $row = $(this).closest('tr'); 
    $.ajax({ 
     type: "POST", 
     url: "${pageContext.request.contextPath}/updateSighting", 
     data: { 
      id: $('input[name="id"]', $row).val(), 
      total_pests: $('input[name="total_pests"]', $row).val(), 
      date: $('input[name="date"]', $row).val(), 
      username: $('input[name="username"]', $row).val(), 
      information: $('input[name="information"]', $row).val() 
     }, 
     success: function(response) { 
      $("#alert").show(); 
      alert("Submitted"); 
      $(".errormsg").hide(); 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert("Status: " + textStatus); alert("Error: " + errorThrown); 
     } 
    }); 
}); 
+0

我剛試圖實現這一點。它仍然沒有設法更新。我確實收到一條提示消息,提示「已提交」,但是當我刷新頁面時,更新的內容不存在。 – Maff

+0

'更新內容'是什麼意思?你的成功處理器顯示/隱藏了一些div元素,它不會對'response'返回做任何事情。 –

+0

我的意思是,當我去到另一個頁面,然後返回到此頁面查看所有列表。我之前在返回此頁面之前更改的行沒有得到更改。 – Maff