ajax与java无法正常工作

时间:2013-07-18 19:00:38

标签: javascript ajax servlets

您好我正在使用servlet来实现我的第二个ajax程序。但它不起作用。请帮忙

    index.html

<!DOCTYPE html>
<html>
<head>
<script>
function callServer(str){
alert(str);
var myxml = new XMLHttpRequest();
myxml.onreadystatechange = function  {
    if(myxml.readyState == 4 && myxml.status == 200)
        document.getElementById("replay").innerHTML = myxml.responseText;
}
myxml.open("GET",""/suggest?query=str",true);
myxml.send();

  }
   </script>
   </head>
   <body>
   <input id="enter" type="text" onkeyup="callServer(this.value)" />
   <div id="replay"></div>
   </body>
   </html>

我的servlet就在这里......

  import java.io.IOException;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  @WebServlet("/suggest")
  public class suggest extends HttpServlet {
public suggest() {
    super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {
    String [] values = {"sha","kla","hello","bun"};
    String query = request.getParameter("query");
    for (int i = 0; i < values.length; i++) {
        if (values[i].equals(query)) 
            response.getWriter().write("OK its available dude... "+query);
        else response.getWriter().write("Sorry not yet... "+query);

    }

}

}

这里我认为错误可能出在js函数callserver中。我已经检查了每一行,并提供了一个警告,以便检查它是否正常工作直到该行                          myxml.onreadystatechane = function。警报一直工作到那里。请帮忙

1 个答案:

答案 0 :(得分:1)

您的网址包含语法错误 请将其更改为:myxml.open(“GET”,“/ suggest?query = str”,true);

我添加了一个符合您要求的教程链接:

http://www.java4s.com/ajax/checking-user-name-availability-with-ajax-google-style/