我正在使用Spring MVC应用程序,用户可以在其中创建和更新任务。当前,当页面加载时,jdbc调用发生在服务器端,并且任务列表已放入模型中并显示在客户端。我正在使用AJAX允许用户更新任务,但我认为这似乎只能与列表中的第一个任务一起使用,因为列表中的每个表单都具有相同的ID。我是AJAX的新手,也不是世界上最出色的客户端开发人员,因此我不确定这是否是一个好的开始。我可以通过什么好的方式使Ajax“识别”每个表单的帖子?我的代码在下面,请注意其主要目的是传达我正在使用的方法,因此请忽略任何错别字,并假设ajax调用在列表中的第一种形式下可以正常工作...

HTML + Thymeleaf代码

<li th:each="task:${tasks}">
    <div th:text="${task.name}"></div>
    <div class="row">
        <form id="updateTask" th:action="@{/updateTask}" th:object="${Task}" method="post">
            <input id="id" th:value="${task.id}"/>
            <input id="name" th:value="${task.name}"/>
            <input id="description" th:value="${task.description}"/>
            <button class="btn waves-effect waves-light green" type="submit" name="saveTask" value="saveTask">
                Save <i class="mdi-content-send right"></i>
            </button>
        </form>
    </div>
</li>


从服务器生成的HTML-出于可读性而被截断

<li>
    <form id="updateTask" method="post" action="/updateTask">
        <input id="id" value="37" />
        <input id="name" value="Scrub the floors" />
        <input id="description" value="Make the floors shiny!" />
        ...
    </form>
</li>
<li>
    <form id="updateTask" method="post" action="/updateTask">
        <input id="id" value="38" />
        <input id="name" value="Walk the Dog" />
        <input id="description" value="Make sure he poops" />
        ...
    </form>
</li>


AJAX代码-注意,为了便于阅读,我修剪了一些内容,因此语法可能并不完美

$('#updateTask').submit(function(event) {

event.preventDefault();

var id = $("#id").attr("value");
var name = $("#name").prop("value");
var description = $("#description").prop("value");

//Make the ajax call
$.ajax({
    url : requestMapping,
    type : "POST",
    data : {
        "id" : id,
        "name" : newName,
        "description" : newDescription
    },

    //handle success
    success : function(response) {
        alert("Task " + id + " has been updated!");
    },

    //handle errors
    error : function(xhr, status, error) {
        alert(xhr.responseText);
    }});
    return false;
});

最佳答案

HTML页面应包含一个具有相同名称的ID。但是您使用的是多个具有相同名称的ID。因此,只有第一个ID的值是-


  id = $(“#id”)。attr(“ value”);


您可以通过限定当前部分并从当前参考中选取值来解决您的问题。


  id = $(this).find(“#id”)。attr(“ value”);


您的密码

$('#updateTask').submit(function(event) {

event.preventDefault();
// this is the current reference of form on which you are performing action.
var id = $(this).find("#id").attr("value");
var name = $(this).find("#name").prop("value");
var description = $(this).find("#description").prop("value");

//Make the ajax call
$.ajax({
    url : requestMapping,
    type : "POST",
    data : {
        "id" : id,
        "name" : newName,
        "description" : newDescription
    },

    //handle success
    success : function(response) {
        alert("Task " + id + " has been updated!");
    },

    //handle errors
    error : function(xhr, status, error) {
        alert(xhr.responseText);
    }});
    return false;
});

10-06 15:58
查看更多