I'm working on an application which retrieves some HTML code from a record in a database. That strings then gets taken and inserted inside of a specific div. Right now I'm accomplishing this by passing the variable from Java and printing it within the div in the JSP. Now I'm trying to use an external jQuery function to accomplish this task and I'm struggling with how to pass this String to the jQuery function.
I tried something like this:
<script>
var message = <%=message %>;
</script>
<script src="files/js.js" type="text/java开发者_Go百科script"></script>
But it can't seem to interpret the var once it hits the external function (I tried using StringEscapeUtils but that didn't fix the issue).
try:
var message = '<%= message %>';
var message = '<%=message %>';
$(message); // we have a jQuery object with a property
// for each html element in the message string!
When you run into problems like this, view the source of your page. How does message
render? My guess might be
var message = Passing an HTML string to jQuery function;
Which isn't valid. Enclosing the code in apostrophies will fix this case.
var message = '<%= message %>';
I also usually put global objects like this on the window object so it is easier to find
window.message = '<%= message %>';
var message= <%= message %>;
You not only need to put some quotes around the message text, you also need to escape it suitably for a JavaScript string literal. Otherwise a quote in the message will break it, and potentially open you up to cross-site scripting attacks.
var message= '<%= message.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") %>';
I think that's the right number of backslashes, but the interaction of Java String literal backslashes and regex backslashes balloons them out of all sanity. Also control codes like newlines would need escaping if you need to include those.
All in all it might be best to hand the task off to a JSON-encoding library which will output all kinds of JavaScript types properly, not just strings. eg. with json-simple:
var message= <%= JSONValue.toJSONString(message) %>;
精彩评论