【问题标题】:Retrieve java object from servlet with ajax and print it with JSTL使用 ajax 从 servlet 中检索 java 对象并使用 JSTL 打印它
【发布时间】:2014-12-16 16:09:37
【问题描述】:

当 jsp 中的选项框发生更改时,我想对我的 TestServlet 进行 ajax 后调用。当这个 servlet 从 ajax 检索到时,servlet 将创建一个新的 person 对象并将其发送回 ajax 调用来自的 jsp 页面。

此时我可以在 id 为 uidrespon <div id="uidrespon"></div> 的 div 中打印此对象,但如何使用<c:out test="${object.name}"/> 或 <c:out test="${object.age}"/> 等 JSTL 输出标签读取此对象

从 jsp 页面到 servlet 的 Ajax 调用:

<script> $(document).ready(function() {   
    $("body").on('change',
    '#personbox', function() {
  //get the selected value
  var selectedValue = $(this).val();

  $.ajax({            type    : 'POST',           url     : '${pageContext.request.contextPath}/secure/TestController.do',
        data  : { "ajaxCallBack" : selectedValue },
        success : function(response) {   
          $('#uidrespon').html(response); 
        },
        error : function(error) {
            alert(error);
        }
    });

  alert(selectedValue);   }); }); </script>

选择下拉菜单:

<select class="form-control" id="rulebox" name="selectPerson" onchange="Change()">
     <option value="">Select rule</option>
     <option value="${dePerson.name}">${dePerson.name}</option>
     <option value="${dePerson.name}">${dePerson.name}</option>
</select>

Servlet 中的 Post 方法:

public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {

        String name = req.getParameter("ajaxCallBack");

        Person nwePerson = new Person();
        nwePerson.setThePerson((List<Person>) getServletContext().getAttribute("allPersons"));

        Persons src = nweFact.findPerson(name);

        req.setAttribute("src", src); 
        resp.setCharacterEncoding("UTF-8"); 
        resp.getWriter().print(src);
    }

【问题讨论】:

    标签: java jquery ajax jsp jstl


    【解决方案1】:

    JSTL 仅适用于服务器端。 Ajax 在客户端工作。您要问的是在 ajax 请求中从 JSTL 刷新 HTML,这是不可能的。

    在响应的返回中以 JSON 格式或类似的格式写入所需的数据,而不是将其存储在 ajax 调用的请求属性中。然后,读取 JavaScript 代码中的响应,将其解析为 JavaScript 对象并使用它。

    【讨论】:

      猜你喜欢
      • 2019-08-14
      • 2012-09-11
      • 2016-11-10
      • 1970-01-01
      • 2015-02-19
      • 2013-05-10
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多