【问题标题】:How can I update a model attribute in JSP from the AJAX response?如何从 AJAX 响应更新 JSP 中的模型属性?
【发布时间】:2017-09-11 05:23:34
【问题描述】:

我有一个这样的 JSP 页面

<li id="notifications">
    <c:choose>
        <c:when test="${empty alerts}">
          <p class="text-default">There are no Service Reminders at this time</p>
        </c:when>
        <c:otherwise>
           <c:forEach items="${alerts}" var="alert">
            <p class="text-default">${alert.serviceItemDescription}</p>
             </c:forEach>
          <button onclick="clearNotifications()" id="clearButton" >clear
       </button>
         </c:otherwise>
    </c:choose>
</li>
  1. 属性 {alerts} 是一个列表。
  2. 我想根据我从以下代码中获得的 AJAX 响应更新此现有列表。
  3. AJAX“结果”是要迭代的新列表。如何通过下面代码中的这个新值“结果”更新现有模型属性“警报”以更新“列表”标签元素?

< script type = "text/javascript" >
  function clearNotifications() {
    $.ajax({
        type: "POST",
        url: "/clearNotifications/" + $ {
          bike.id
        },
        headers: {
          "Accept": "text/html,application/json"
        },
        success: function(result) {
          $("#notifications").html(result);
        }
      }
    });
} </script>

【问题讨论】:

  • 是的,您可以按照您的指示进行更新,但您希望服务器的响应是 HTML 而不是 json。 HTML 是 select/options html 标记和数据
  • 您应该从服务器端发送json数据并通过循环更新jsp中的列表。在循环解析该 json 字符串之前。
  • @ScaryWombat 我将 dataType: 更改为“html”。我从 AJAX 响应中获取空列表,在我的情况下,它必须显示 条件标记中的内容,但是当我单击按钮时,它会在屏幕上显示 [] 符号,而不是 条件标记中的内容。我做错了什么/我该如何实现?
  • 在页面的初始加载(服务器端)上完成标记的时间 - 当您执行 ajax 时,您正在客户端处理,不会再评估 jsp 标记。您返回的结果应该是纯 HTML(在这种情况下),因此可以使用纯 HTML 更新 dom

标签: javascript java jquery ajax jsp


【解决方案1】:

你可以试试这个,

在你的Jsp中,将li改成如下,

<li id="notifications">

</li>

你可以玩js,专门进ajax,

这是最初用于页面加载的,

<script type="text/javascript">

    $(document).ready(function() {
        alerts = ${alerts};
        populateNotification();
    });

function populateNotification(alerts)   {

    for(var i=0; i<alerts.length; i++){
        $("#notifications").html("<p class='text-default'>${alerts[i].serviceItemDescription}</p>");        
    }

    $("#notifications").append("<button onclick='clearNotifications()' id='clearButton' >clear     </button>");
}

这是用于 Ajax 调用的,

function clearNotifications() {
    $.ajax({
        type: "POST",
        url: "/clearNotifications/" + $ {
          bike.id
        },
        headers: {
          "Accept": "text/html,application/json"
        },
        success: function(result) {
          //$("#notifications").html(result);
          alerts = result;
          populateNotification(alerts);
        }
      }
    });
</script>

【讨论】:

  • 谢谢@Desing.. 实际上我已经在AJAX调用检查POST是否成功的方法中将返回值“result”修改为布尔值,所以下面的代码对我有用,我还没有尝试过你的,但如果我在“结果”中返回一个列表,看起来你的解决方案更优雅。刚刚重新加载了带有 id 通知的 List 标记。 success: function (result) { if (result === true) { $("#notifications").load(" #notifications"); } }
猜你喜欢
  • 2017-07-23
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多