简体   繁体   中英

Ajax and jstl, servlet setAttribute and foreach in jsp inside javascript

I got this ajax function which fetches some information from my servlet. I need to display this info in multiple rows. So before I start making some crazy long String and start working on it with javascript, I wanted to hear if it's possible to do something like below.

Basically this ajax function asks my servlet for a list, which I'd like my c:forEach to display on success.

        $.ajax({
                type: "POST",
                url: "eventHandler",
                data: {"action" : "searchCards"},
                success: function(data){  
                    <c:forEach items="${Cards}" var="c"> 
                        $(".rightWrapperDisplaySearch").append(${c.color});
                    </c:forEach>     
                },
                error : function() {
                    Announce("Error!");     
                },
            });

My servlet method

String searchCriteria = request.getParameter("value");          

            LIST = (ArrayList<Cards>) DAO.findAllCards();

            request.setAttribute("Cards", LIST);
            request.getRequestDispatcher("/WEB-INF/jsp/view/All/startPage.jsp").forward(
                    request, response);

Yes, mixing JSTL with Javascript is possible, if the purpose of JSTL is to dynamically construct the Javascript code. Server side code (thru JSTL) is generated first before client side is executed (Javascript). I don't see any conflict with the dollar $ notation used by EL (expression language) and by JQuery.

JQuery uses $()

EL uses ${}

I just found the solution at this link

You cannot do that since javascript executes on client & JSP executes on server side.

If you want to set javascript variable to JSP session, then you pass this variable through the URL like this

 var number = 7;
    window.location="http://example.com/index.jsp?param="+number;

Now receive this var in your JSP page like this

String var = request.getParameter("param");

Now set it in session

  session.setAttribute("test", var);

Now you can't use below lines of code:

var number = 7;
<%session.setAttribute("test", number);%>

In the above code, server will only execute the code inside <% %>. It does not know anything outside of the JSP tags. So, it will also dont know about your javascript variable number.

Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;

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