从 SQL 获取数据并放入 jquery

get the data from SQL and put in jquery

我正在尝试在 jsp 处执行自动完成文本框。但是我不知道如何包含从数据库中检索到的所有数据以用于匹配用户键入的值。请帮忙,非常感谢。

  <%
    String FRUIT= "";

    TEST.makeConnection();
    String SQL = "SELECT * FROM TB_FRUIT WITH UR";
    TEST.executeQuery(SQL);     
    while(TEST.getNextQuery())
    {
        FRUIT= TEST.getColumnString("FRUIT_DESCP");
    }   
    TEST.takeDown();    
   %>

  <html>
  <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
   <script>
    $(function() {
    var availableTags = [
      //how can i include the data(FRUIT) from database to put in here? 

      "Apple", // i hardcode this to do testing for my current autocomplete textbox
      "Avocado", // i hardcode this to do testing for my current autocomplete textbox
      "Banana",// i hardcode this to do testing for my current autocomplete textbox
      "Durian",// i hardcode this to do testing for my current autocomplete textbox
      "Mango",// i hardcode this to do testing for my current autocomplete textbox
    ];
    $( "#tags" ).autocomplete({
        source: availableTags
      });
    });
  </script>      
  <body>
       <div class="ui-widget">
         <label for="tags">Tags: </label>
         <input id="tags">
       </div>
  </body>
  </html>

我不是 JSP 专家,但我想我可以在您的代码中发现几个问题:

  1. FRUIT 将始终具有查询中最后一条记录的值,因为您没有连接这些值,而是用新值替换该值。

    您希望 FRUIT 成为这样的字符串列表:"fruit1","fruit2","fruit3",...,为此,您应该这样做:

    FRUIT += "\"" + TEST.getColumnString("FRUIT_DESCP") + "\",";
    
  2. 即使您正确获取了值,您也不会在网站上显示它。现在您已经以自动完成可以理解的格式获得了 FRUIT 的值,您只需要打印它:

    var availableTags = [
        <% out.print(FRUIT); %>
    ];
    

这应该可以解决问题。

最后,代码将如下所示:

<%
    String FRUIT= "";

    TEST.makeConnection();
    String SQL = "SELECT * FROM TB_FRUIT WITH UR";
    TEST.executeQuery(SQL);     
    while(TEST.getNextQuery())
    {
        FRUIT += "\"" + TEST.getColumnString("FRUIT_DESCP") + "\",";
    }   
    TEST.takeDown();    
   %>
  <html>
  <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
   <script>
    $(function() {
    var availableTags = [
        <% out.print(FRUIT); %>
    ];
    $( "#tags" ).autocomplete({
        source: availableTags
      });
    });
  </script>      
  <body>
       <div class="ui-widget">
         <label for="tags">Tags: </label>
         <input id="tags">
       </div>
  </body>
</html>