如何用jsp Java数组传递到JavaScript数组? [英] How to transfer java array to javaScript array using jsp?

查看:719
本文介绍了如何用jsp Java数组传递到JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的服务器上的琴弦,我想获得到客户端在一个数组形式的列表。在code我试图用的是以下内容:

I have a list of strings on my server which I am trying to get to the client in the form of an array. The code I am attempting to use is the following:

在jsp中我有一个列表与LT;弦乐>

我在尝试以下code:

I am attempting the following code:

<%int j = 0; %>
for(var i = 0; i < <%=columns.size()%>; i++)
{
  colArray[i] = "<%=columns.get(j++)%>";
}

这code简单地返回列列表中的第一个元素在colArray每个元素。

This code simply returns the first element in the columns list for every element in the colArray.

我也尝试:

colArray = <%=columns.toArray()%>;

这也不起作用。
我觉得我做的地方一点点错误,我只是没有看到它。是什么,我想在我试图顺便做可能吗?

which does not work either. I feel like I am making a little mistake somewhere and am just not seeing it. Is what I am trying to do possible in the way that I am attempting?

感谢。

推荐答案

你越来越被混在一起是那样的客户端上执行的JavaScript code中的服务器上执行的JSP code。该段&LT;%= columns.get(J ++)%GT; 被执行一次,在服务器上,并围绕它的JavaScript循环是无关紧要的在这一点上。当它到达客户端,循环体只是说 colArray [I] =第一项; 这当然使相同的字符串到数组中的每一个元素

You're getting the JSP code that is executed on the server mixed up with the JavaScript code that's executed on the client. The snippet <%=columns.get(j++)%> is executed once, on the server, and the JavaScript loop around it is irrelevant at this point. When it arrives the the client, the loop's body just says colArray[i] = "first entry"; which of course puts the same string into every element of the array.

你需要做的,而不是什么是有一个循环在服务器上执行,像这样的:

What you need to do instead is to have a loop execute on the server, like this:

<% for (int i=0; i<columns.size(); i++) { %>
colArray[<%= i %>] = "<%= columns.get(i) %>"; 
<% } %>

我的JSP技术是生锈,和语法可能不同,但我希望你的想法。

My JSP skills are rusty, and the syntax may be different, but I hope you get the idea.

编辑:由于在评论中指出,你必须要非常小心转义这些字符串任何可能导致他们PTED如JavaScript code间$ P $(最突出引号) - 特别是如果它们包含用户生成的内容。否则,你要离开你的应用程序敞开跨站点脚本和的Cross-site请求伪造攻击

As was pointed out in the comments, you need to be VERY careful about escaping anything in those Strings that could cause them to be interpreted as JavaScript code (most prominently quotation marks) - especially if they contain user-generated content. Otherwise you're leaving your app wide open to Cross-site scripting and Cross-site request forgery attacks.

这篇关于如何用jsp Java数组传递到JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆