gpt4 book ai didi

java - 通过 JSP 表单插入新项目后更新列表

转载 作者:行者123 更新时间:2023-11-30 17:31:46 24 4
gpt4 key购买 nike

在我的 Spring 项目中,我以这种方式将一个列表从我的 Controller 传递到我的 JSP 页面:

mav.addObject("tipos", tipo.listaTipos());
mav.addObject("campos", atributo.listaKey());

在 JSP 页面中,除了显示这些项目外,我还可以添加新项目,如下面的代码(包括 HTMl 和 Jquery)所示:

HTML

<table class="bordered campos" id="edit_campos">
<thead>
<tr>
<th>Campo</th>
<th>#</th>
</tr>
</thead>
<tfoot>
<tr>
<td> <input type="text" name="nome_campo"> </td>
<td> <button type="button" id="incluir_campo" class="btn btn-link">Incluir</button> </td>
</tr>
</tfoot>

<c:forEach var="item_key" items="${campos}">
<tr id="linha_${item_key.id}">
<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>
<td> <button type="button" id="excluir_campo" class="btn btn-link">Excluir</button> </td>
</tr>
</c:forEach>
</table>

JQuery

$("#incluir_campo").on("click", function () {
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/cadastra_campo"/>",
data: {nome: $("input[name=nome_campo]").val() }
}).done(function(data){
if(data=="yes") {
var newRow = $("<tr>");

cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';

newRow.append(cols);
$("table.campos").append(newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
}).fail(function(){
alert("falha ao incluir campo");
});
});

但是,在当前这种情况下,新行显示时没有内容,因为传递给 JSP 的列表保持不变。插入新项目后如何更新传递给 JSP 的列表?

最佳答案

看看这些行:

cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';

当您动态使用 DOM 元素(如插入新元素、更新 DOM 等)时,不要在 Jquery 中使用表达式(${}),当 jsp已处理/呈现的 HTML。

解决方案是:

在 Controller 中获取新项目后,将其添加到列表中,并返回与 AJAX 响应相同的项目,然后将其附加到现有表中。喜欢:

考虑您的 Controller 方法以 json 格式返回数据,例如:

var data = {"item_key" : {nome : "abc"}, "item_campo" : {id : "1"}};

然后完成:

.done(function(data){
if(data.length != 0) {

var $newRow = $("<tr>");
var $newTextbox = $('<input type="text" id="'+data.item_key.nome+'" name="foo">');
var $newButton = $('<button type="button" id="excluir_campo_'+data.item_campo.id+'" class="btn btn-link">Excluir</button>');

$newRow.append($('<td>').append($newTextbox));
$newRow.append($('<td>').append($newButton));

$("table.campos").append($newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
})

jsfiddle

关于java - 通过 JSP 表单插入新项目后更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com