简体   繁体   中英

Get escaping error when putting JSTL variable into Javascript

I follow this post to render a javascript variable using JSTL variable:

var size= "<c:out value='${fn:length(orders)}'/>";

However, not quite lucky, I get an exception like this:

Element type "size" must be followed by either attribute specifications, ">" or "/>".

So I use

var size= &lt;c:out value='${fn:length(orders)}'/&gt;;

instead, but no luck. After add double quote:

var size= "&lt;c:out value='${fn:length(orders)}'/&gt;";

Still not working..So how to escaping and make it work?

UPDATE 1

The jspx is looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jsp:root 
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields" 
    xmlns:jsp="http://java.sun.com/JSP/Page" 
    xmlns:page="urn:jsptagdir:/WEB-INF/tags/form" 
    xmlns:spring="http://www.springframework.org/tags" 
    xmlns:form="http://www.springframework.org/tags/form" 
    xmlns:fn="http://java.sun.com/jsp/jstl/functions" 
    xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
    version="2.1">
<div>
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<jsp:output omit-xml-declaration="yes"/>

<page:show>
   <form:form.....
    <!--body of the form -->
   </form:form>
</page:show>

<script type="text/javascript">
    //jquery and so...
    ....
    var size= "<c:out value='${fn:length(orders)}'/>";
    ....
</script>

</div>
</jsp:root>

Based on the answer of the link of the post , it would be better if you first define a variable with your needs and then use the value of that variable in JavaScript:

<c:set var="ordersLength" value="${fn:length(orders)}"/>
<script type="text/javascript">
    var size= "<c:out value='${ordersLength}'/>";
</script>

Another option would be setting the value of ${fn:length(orders)} in a hidden field and read this field value in JavaScript:

<input type="hidden" id="ordersLength" value="${fn:length(orders)}" />
<script type="text/javascript">
    var size = document.getElementById('ordersLength').value;
</script>

Of course, this last option is clumsy but might help you to solve this issue.

If none of these work it means your orders variable isn't set nor as request attribute nor as session attribute nor as application attribute nor as page attribute (and by the provided code in your answer, we aren't capable to help you with that [yet]).

You can't get it to work with jspx files. You can with jsp files.

jspx files require well formed XML. The XML is validated before the EL is processed, and so your code fails.

See this post for better a explination

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