使用 jsp 和 scriplets 自动完成(不使用 java 类)

Autocomplete using jsp and scriplets(Not using java classes)

我想进行自动完成,但不想使用任何 java 方法。只需使用 jsp、jquery、ajax 和 scriplet。可能吗?请提出建议。

我尝试使用下面给出的代码,但出现错误

未捕获错误:无法在初始化之前调用自动完成方法;试图调用方法 'List.jsp'

代码如下:

//(Index.jsp)

<html>
<head>

<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#country').focusin(function() {
$("#country").autocomplete("List.jsp");
});
});
</script>
</head>
<body>
    <br><br><center>
        <font face="verdana" size="2">
        <font size="4">Java(jsp)/jQuery Autocompleter Example</font>
        <br><br><br><br>

        Select Country   :
        <input type="text" id="country" name="country"/>

        </font>
    </body>
</html>

//(List.jsp)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>

<%
    try {
        String s[] = null;

        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
        String url = "jdbc:mysql://localhost:protNum/dbName";
        String user = "";
        String pass = "";
        System.out.println("Connected....");
        Connection con = (Connection) DriverManager.getConnection(url, user, pass);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from tbctry");

        List li = new ArrayList();

        while (rs.next()) {
            li.add(rs.getString(1));
        }

        String[] str = new String[li.size()];
        Iterator it = li.iterator();

        int i = 0;
        while (it.hasNext()) {
            String p = (String) it.next();
            str[i] = p;
            i++;
        }

        //jQuery related start
        String query = (String) request.getParameter("q");

        int cnt = 1;
        for (int j = 0; j < str.length; j++) {
            if (str[j].toUpperCase().startsWith(query.toUpperCase())) {
                out.print(str[j] + "\n");
                if (cnt >= 5)// 5=How many results have to show while we are typing(auto suggestions)
                {
                    break;
                }
                cnt++;
            }
        }
 //jQuery related end

        rs.close();
        st.close();
        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
%>

我希望文本框在按键时自动填充数据库中的值。我已经使用 spring MVC 完成了此操作,但我不知道如何在不使用任何 java class 的情况下执行此操作,而是仅使用 jsp、jquery、ajax 和 scriplets。请帮忙!

您可以通过使用 jquery onkeyup 事件来做到这一点,当用户开始在输入框中输入时,输入的值将传递给您的 jquery 函数并使用 ajax 您可以调用 List.jsp 页面并使用 request.getParameter("") 获取该值,最后在您的查询中传递该值,然后 return 使用 out.print 返回结果,如下所示:

输入 即:输入值的位置:

    Select Country   :  <input type="text" id="country" name="country"/>
  //here result will be display
    <div id="result"></div>

Jquery & Ajax :

 <script>
     $('#country').keyup(function(){
       //getting typed value
            var searchid=$(this).val();
               if(searchid!='')
                     {
                        $.ajax({
                           type:"POST",
                            url:"List.jsp",
                            //passing value
                             data:{search:searchid},
                             success:function(html){
                            //response from List.jsp page will come here                                       
                                $('#result').html(html);
                            }
                         });
                         } 
                   });
        </script> 

List.jsp 页面 :

//getting value passed from ajax
 String search = (String) request.getParameter("search");
//db setting
      try{
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
        String url = "jdbc:mysql://localhost:protNum/dbName";
        String user = "";
        String pass = "";
        System.out.println("Connected....");
        Connection con = (Connection) DriverManager.getConnection(url, user, pass);
          //below columnanme is fieldname from where you need to compare your search value.
        PreparedStatement pstmt = con.prepareStatement(
         "select * from tbctry where columnname LIKE ?");
         pstmt.setString(1, search + "%");
         ResultSet rs=pstmt.executeQuery();  
         while(rs.next()){ 
        //here you need to print values which you need to show in div 
         out.print("something"); 
          }
        rs.close();
    pstmt.close();
    con.close();

} catch (Exception e) {
    e.printStackTrace();
}

希望对您有所帮助!

List.jsp页数

<%@page import="java.util.*" %>
<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.parser.JSONParser"%>
<%@page import="org.json.simple.parser.ParseException"%>
<%@ include file = "connect.jsp"%>

<%

//getting value passed from ajax
 String search = (String) request.getParameter("search");
    try{
        JSONArray dataArray = new JSONArray();
        JSONObject item = null;
        PreparedStatement pstmt = con.prepareStatement("select * from LPRONE.POINFO where PONO LIKE ?");
         pstmt.setString(1, search + "%");
         ResultSet rs=pstmt.executeQuery();  
         while(rs.next()){ 
            item = new JSONObject();
            item.put("name", rs.getString(12));
            dataArray.add(item);
          }
        //here you need to print values which you need to show in div
        out.println(dataArray); 
    } catch (Exception e) {
        e.printStackTrace();
    }

%>

我使用 JSONObject 和 JSONArray 获取结果集并通过 out.ptintln() 将其传递给调用 jsp 页面。

Input.jsp页数

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script src="jquery/jquery-1.7.min.js"></script>
    <script src="jquery/jquery.autocomplete.min.js"></script>
        <script src="jquery/jquery-ui.js"></script>
        <title>JSP Page</title>
    </head>
    <body>
<div class="form-group">
  Select Country   :  <input list="newlist" type="text" id="PO" name="PO"/>
  //here result will be display
    <datalist id="newlist"></datalist>
</div>

  <script>
     $('#PO').keyup(function(){
       //getting typed value
            var searchid=$(this).val();
               if(searchid!='')
                     {
             $(function(){
             $("#PO").autocomplete({
             source:function(request, response){
                        $.ajax({
                           type:"get",
                            url:"List.jsp",
                            //passing value
                             data:{search:searchid},
                             success:function(response){
                            //response from List.jsp page will come here     
                var obj = JSON.parse(response);
                if(!obj){

                }
                else{
                var dl = document.getElementById("newlist");
                dl.innerHTML="";
                for(var i=0; i<obj.length; i++)
                {
                var opt=document.createElement('option');
                dl.appendChild(opt);
                opt.innerHTML = opt.innerHTML + obj[i].name;
                }

                }
                            }
                         });
             }
             });
             });
                         } 
                   });
        </script> 

    </body>
</html>

这里我绑定了 ajax 调用成功的值。这是使用 jsp、jquery、ajax、脚本、JSON 和自动完成功能的自动完成示例。没有使用 servlet。