[英]How can I use variables declared in javascript inside Java code?
I am making a website that gets some data from a database using SQLite. 我正在建立一个使用SQLite从数据库中获取一些数据的网站。 In order to connect to the database, I use the following Java code inside a jsp file.
为了连接到数据库,我在jsp文件中使用以下Java代码。
<%
String[] nameArray;
nameArray = new String[10];
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:d:\\Databases\\DataBase1.db");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from users;");
int i = 0;
while (rs.next()) {
nameArray[i] = rs.getString("name");
i++;
}
rs.close();
conn.close();
%>
It creates an array that stores the information from the database. 它创建一个数组,用于存储数据库中的信息。
Next, I have this Javascript code that is supposed to change an element from my page to the values of the previous array 接下来,我有此Javascript代码,该代码应将页面中的元素更改为上一个数组的值
<script type="text/javascript">
var nameField = document.getElementById("nameField");
var passwordField = document.getElementById("passwordField");
var admin;
function CheckName() {
for(j = 0; j < 10; j++) {
document.getElementById("result").innerHTML = "<%=nameArray[j]%>"; //ERROR here, I can not use "j" as a value
}
}
</script>
The problem is, I can't use the "j" variable as an array indicator. 问题是,我不能将“ j”变量用作数组指示符。
How can I solve this problem? 我怎么解决这个问题?
This is what I would do as it is not possible to use javascript variables inside java. 这是我会做的,因为无法在Java中使用javascript变量。 Let List is your result from the Data base.
让列表是您从数据库获得的结果。 If you do not use use expression language(el) which it seems, just put the code where you want the result to be displayed.
如果您不使用看起来似乎的表达语言(el),则只需将代码放在希望显示结果的位置即可。
Do not forget to import List and ArrayList into your jsp in the following way 不要忘记通过以下方式将List和ArrayList导入到jsp中
<%@ page import ="java.util.ArrayList"%>
<%@ page import ="java.util.List"%>
<% List<String> list = new ArrayList<>();
list.add("Name1");
list.add("Name2");
list.add("Name3");
%>
<% for(int j=0; j < list.size(); j++){ %>
<p id="result"><%=list.get(j)%></p>
<%}%>`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.