Velocity - How to avoid ParseErrorException when using jQuery?

蹲街弑〆低调 提交于 2019-12-02 23:38:33

You can wrap your javascript with #[[ ... ]]# which tells Velocity to not parse the enclosed block (new in Velocity 1.7)

#[[ 
<script>
    ...
</script>
]]#

Ok, there appears to be two solutions for this:

First, with jQuery we can just avoid using the global alias $ and instead use the jQuery object directly:

jQuery.post(url, myJSONObject, function(result){
~~~snip~~~

In my case, the above works great. But I suspect in other scenarios (non-jQuery) this may not be possible. In which case, we can 'hide' our character within a valid Velocity reference like this:

#set( $D = '$' )
${D}

Source: http://velocity.apache.org/engine/devel/user-guide.html#escapinginvalidvtlreferences

I'd still like to know why the backslash escape didn't work, but the above will at least get me moving again. :)

I think this is a bug in version 1.6.x, because it works fine in 1.7(If it did not, please tell me, I test it many times..), according to the reference, the $ takes effect only when it is followed by a-zA-Z. I want to try do debug what happened really, but the translation code is generated by Java CC tool, it is too hard to recognize the logic...

you must create a js file with your javascript code and import your js file into your vm code

I couldn't get it to work with any of the other fixes like escaping "$" in velocity unfortunately. I got it working by loading an external js-file with the jQuery instead of writing jQuery directly in velocity. Worked out for me at least, hope it helps someone :)

/björn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!