Velocity array to javascript array

牧云@^-^@ 提交于 2019-12-02 01:57:00

问题


I need to pass a velocity string array to JavaScript function. So, for that, I want to convert the velocity array into JavaScript array.

The source code looks like this :

String[] arrStr[] = new String[3];
arrStr[0] = "String 1";
arrStr[1] = "String 2";
arrStr[2] = "String 3";
request.setAttribute("a", arrStr);

In my HTML template,

#set ( #arr = $request.getAttribute("a"))

<script language="javascript">

var newArr = "${arr}";

</script>

But the string arrays are not copied to newArr. Can anyone help me out on this ?


回答1:


This is a really good question, I tried countless solutions and nothing that seemed reasonable couldn't make an array of strings, everything resulted in [param1, param2] instead of ["param1", "param2"] and to an error "param1 is not defined".

However I was able to resolve it by using #foreach as a parameter and rest parameter.

In HTML:

functionName(
  #foreach($obj in $array)
      #if ($velocityCount != $array.size())'$obj',
      #else'$obj'
      #end
  #end
)

In Javascript:

functionName(...args) 

...args is a rest parameter, which "represents an indefinite number of arguments as an array". So if you need other parameters besides the array, remember to put them before the array:

functionName(param1, param2, ...args)



回答2:


Something like:

var newArr = [ 
#foreach( $var in $arr )#if($foreach.index>  0),#end "$var" #end 
]; 


来源:https://stackoverflow.com/questions/10527883/velocity-array-to-javascript-array

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