我的javascript代码的post函数不能按预期工作

时间:2014-05-29 08:03:36

标签: javascript jquery html jsp

我对javascript有疑问。

我必须使用位于html文件头中的javascript代码中的post函数将queryString变量中的数据发送到位于本地服务器中的autocom.jsp文件,然后使用回调从本地数据库中获取数据功能,功能(数据){}。

我的问题是,当我在html页面的输入字段中输入c时,网页上会显示测试确定,即使在我的数据库中我没有姓氏数据列(在数据库中称为last),以字母c开头。这应该永远不会发生,因为在这种特殊情况下data.length> 0不正确。

有人可以帮我解决这个问题吗?

由于

html文件位于search.html下面:

<html>

<head> 

<link href="styles.css" type="text/css" rel="stylesheet" />

<script type="text/javascript" src="jquery-1.4.2.js"></script>


<script type="text/javascript">
 function checkSubmit (thisForm) {
  if(thisForm.last.value=='') {
     alert('Please Enter Last Name');
     return false;
  } 
 }
</script>



<script type="text/javascript">
function lookup(inputString) {
           if(inputString.length == 0) {
              out.println("testing go");
           } else {
                $.post("autocom.jsp", {queryString: "" +inputString+ ""}, function(data){
                    if(data.length >0) {
                       $('#suggestions').show();
                       $('#autoSuggestionsList').html(data);
                       $('#autoSug').html('<h1>testing ok</h1>');
                    }
               });
             }
 }
</script>





</head> 

<body> 

<form method="post" action="search.jsp" onsubmit="return checkSubmit (this);">
Enter Last Name: <input type="text" name="last" value="" id="suggestions" id="autoSuggestionsList" onkeyup="lookup(this.value);" /><br>
<input type="submit" value="Submit">
</form>

<p id="autoSug">  </p>


<form method="post" action="home.html"> 
<input type="submit" value="Back To Home">
</form>


</body>


</html>

以下是autocom.jsp文件:

<%@ page language="java" import="java.sql.*" %>

<% response.setContentType("text/html");%>

<%

String str=request.getParameter("queryString");


String connectionURL = "jdbc:mysql://localhost/jsptest";
Connection con;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root", "Dummy123");  // Get a Connection to the database
String sql = "SELECT last FROM employees WHERE last LIKE ' " +str+  " % ' LIMIT 10 "; //Add the data into the database
Statement stm = con.createStatement();
stm.executeQuery(sql);
ResultSet rs= stm.getResultSet();
 while (rs.next ()){
     out.println(  "<i onclick='fill("  +  rs.getString("last")  +   ");'>" +rs.getString("last")+ " </i>" );
 }


%>

1 个答案:

答案 0 :(得分:-1)

您有<% %>个标记之外的新行,因此您的JSP将输出换行符。这些将使data字符串的字符串长度超过0个字符。