简体   繁体   中英

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. In order to connect to the database, I use the following Java code inside a jsp file.

<%
     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

<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.

How can I solve this problem?

This is what I would do as it is not possible to use javascript variables inside java. 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.

Do not forget to import List and ArrayList into your jsp in the following way

 <%@ 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>
<%}%>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM