简体   繁体   中英

Retrieve java object from servlet with ajax and print it with JSTL

When a option box changed in jsp I want to do an ajax post-call to my TestServlet. When this servlet retrieved the from ajax the servlet will create a new person object and send it back to the jsp page where the ajax call comes from.

At this moment I can print this object in a div with the id uidrespon <div id="uidrespon"></div> , but how can I read this object with a JSTL out tag like <c:out test="${object.name}"/> or <c:out test="${object.age}"/>

Ajax call from jsp page to servlet:

 <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 dropdown:

<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>

Post method in Servlet:

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);
    }

JSTL works on server side only. Ajax works on client side. What you're asking is to refresh HTML from JSTL in an ajax request, which is not possible.

Write desired data in the return of the response in JSON format or something similar in the response rather than storing it in request attribute for the ajax call. Then, read the response in your JavaScript code, parse it into a JavaScript object and work with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM