Error using Javascript and JSP, string with space gives `Unterminated string literal`
I have to pass a string value to JavaScript from JSP page.
I am usingdisplay("<%=name%>")
It works fine 开发者_如何转开发but when i have string like 'sweet milk'
, JavaScript throws the error
Unterminated string literal
How to solve this?
Your string contains single quotes - you can escape single quotes as "\x27" and double quotes as "\x22" and then pass it to javascript.
You probably have characters in your String that should be escaped in Javascript. For example, if your string is My name is "John"
, your code will generate
var a = "My name is "John"";
which is invalid.
You should use StringEscapeUtils.escapeJavaScript from commons-lang to make sure everything is correctly escaped (single and double quotes, newlines, tabs, etc.).
I guess there's an error in the generated JavaScript code. Is there any way to look at you page? I suggest to look at the generated source code of that page.
精彩评论