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

时间:2014-04-06 23:16:09

标签: java javascript jquery jsp

在我的Spring项目中,我以这种方式从控制器向List页面传递一个List:

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的列表?

1 个答案:

答案 0 :(得分:2)

看看以下几行:

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元素(如插入new,更新DOM等)动态使用时,不要在 Jquery 中使用表达式(${}),在处理/呈现jsp的jsp时评估表达式。

解决方案将是:

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

考虑你的控制器方法在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

相关问题