开发者

Passing Java String with multiple lines to a javascript function ( using Velocity)

I'm trying to pass a String variable into my javascript function, but my variable has a multiple lines: For example :

String info = "aaaa \n bbb \n ccc";

I need this form to properly display it. And now I have开发者_运维百科 a "result" Java Object with info field and I can't pass this to my javascript function.

popupErrors('$!{result.info}')" 

The problem is that result.info is put here as a whole text with new lines. How can I solve this problem?


Maybe popupErrors is displaying the string an an HTML popup instead of say a javascript alert. So the new lines are not getting show, you'd need to replace \n with <br/> so they show up in HTML. OR Maybe $!{result.info} is automatically HTML encoding your \n to &#010;


You need to escape the string to Javascript format:

popupErrors('$esc.javascript($result.info)') 


You need to transform your String so that all the JavaScript special characters (end of line, ", ', tabs, etc.) are escaped (\n, \", \', \t, etc.).

Commons-lang has StringEscapeUtils.escapeEcmaScript to do this. Encapsulate this method inside a JSP tag, or escape the string in your controller.


replace \n with space.

Str.replace("\n"," ");

Then pass the string to javascript function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜