如何在java脚本数组中设置jsp变量
How to set jsp variable in java script array?
嗨,我正在尝试将jsp变量设置为javascript数组。我尝试过,但在运行代码时无法实现。我没有得到我的输出,我只看到一个空白屏幕。
这是我的代码:
value.jsp
<script>
<%
URL url;
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
List commodity = null;
List pric = null;
int c = 0;
int p = 0;
try {
// get URL content
String a = "http://122.160.81.37:8080/mandic/commoditywise?c=paddy";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null)
{
System.out.println(inputLine);
// sb.append(inputLine);
String s=inputLine.replace("|", "'n");
s = s.replace("~"," ");
StringTokenizer str = new StringTokenizer(s);
while(str.hasMoreTokens())
{
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
list1.add(mandi);
list2.add(price);
}
}
commodity = list1.subList(0,10);
pric = list2.subList(0,10);
for (c = 0,p = 0; c < commodity.size()&& p<pric.size(); c++,p++)
{
String x = (String)commodity.get(c);
String y = (String)pric.get(p);
//out.println(y);
//out.println(x);}
%>
jQuery(function ($) {
var roles = [];
roles.push(<%= x%>)
roles.push(<%= y%>)
<%
}
%>
var counter = 0;
var $role = $('#role')
//repeat the passed function at the specified interval - it is in milliseconds
setInterval(function () {
//display the role and increment the counter to point to next role
$role.text(roles[counter++]);
//if it is the last role in the array point back to the first item
if (counter >= roles.length) {
counter = 0;
}
}, 400)
});
</script>
<%
br.close();
//System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
如何实现我想要的输出?
当您从JSP输出到JS时,您必须确保您的输出是有效的JS。
您当前的输出将输出一个不带引号的字符串,JS解释器将其视为JS代码,而不是您想要的字符串或数组。
此外,您正在制作10份JS
jQuery(function ($) {
var roles = [];
roles.push(<%= x%>)
roles.push(<%= y%>)
并且该函数永远不会关闭。
我会寻找一个不错的JSON输出库。这会大大简化你的生活。
每次循环时,似乎都在清除角色变量var roles = [];
。
您可能需要考虑不发布整个文件,而是将示例与您需要帮助的部分配对。
您还可以将数组放入JSON对象中,并在javascript中解析该对象。这可能是一个更干净的实现。
尝试用类似roles.push("<%=x%>"(的引号将scriptlet括起来,并检查数组初始化。
相关文章:
- 在IFrame中对jsp的onload是将IFrame设置为整个页面/浏览器
- 在不重新加载页面的情况下,从JSP(服务器端)b设置一个JavaScript变量
- 如何在呈现之前在jsp中将textfield的值设置为会话属性
- 如何使用按钮的jsp点击事件将属性设置为struts-bean
- 使用Set属性在JSP:UseBean中设置javascript变量值
- 使用 JSP 设置 HTML5 会话存储<键,值>
- 如果在第一个 jsp 页面设置了刷新参数,则会刷新所有 jsp 页面
- Struts2 到 ajax json 响应如何在 Jsp 页面上设置图像
- 在 JSP 中设置一个值,从 javascript 传递给 JSTL 的模态
- 设置宽度和高度 jsp 页面
- 调用 java 方法,从 jsp 中的下拉列表选择中设置参数值
- 在渲染 JSP 页面后设置 ng 模型
- 当index.jsp被设置为欢迎文件时,CSS和JS不会被呈现
- 如何在JSP中设置下拉菜单的选择更改值
- 设置jsp上的Ajax响应不起作用
- 如何从Javascript在JSP中设置textfield的值
- 如何设置自动完成输入框的值,而使用Jquery自动完成与JSP
- 不能读取property 'removeChild'使用JSP设置null
- 设置间隔功能在jsp中不起作用
- 如何在java脚本数组中设置jsp变量