如何从jQuery的$ .ajax()函数调用servlet

Ank*_*kur 4 javascript ajax jquery post servlets

我试图从jQuery的.ajax()函数调用一个servlet.

目前我不认为我甚至不会调用servlet或将paramaters传递给它,但是很多Google搜索似乎没有帮助.有任何想法吗?

这是我的HTML:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function login(){  

  $("#loading").hide();

  var email = document.nameForm.email.value;  
  $.ajax({  
    type: "GET",  
    url: "ProcessForm",  
    data: "email="+email,  
    success: function(result){  
      alert(result);
    }                
  });  
}        
</script>
<title>My AJAX</title>
</head>
<body>
<p>This time it's gonna work</p>
<form name="nameForm" id="nameForm" method="post" action="javascript:login()">
Run Code Online (Sandbox Code Playgroud)

电邮加载

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

还有我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ajaxtry</display-name>
  <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
<servlet-name>ProcessForm</servlet-name>
<servlet-class>com.ajaxtry.web.ProcesFormServlet</servlet-class>
  </servlet>
   <servlet-mapping>
<servlet-name>ProcessForm</servlet-name>
<url-pattern>/ProcessForm</url-pattern>
  </servlet-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)

servlet目前只是一个模板:

package com.ajaxtry.web;

// imports here

public class ProcessFormServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    System.out.println(request.getParameter("email")); 
  }
}
Run Code Online (Sandbox Code Playgroud)

mpo*_*ien 10

这里有几个问题:

您正在调用System.out.println,它只是将输出发送到标准输出 - 而不是发送到浏览器.尝试将"System.out.println"更改为"out.println"

看起来你已经在你的servlet代码中定义了doPost(),但你的javascript使用的是"GET"方法.将doPost()重命名为doGet(),或者同时定义它们.

话虽这么说,你可能根本不应该打扰javascript,直到你实际上让servlet工作,保持简单.您应该能够通过在浏览器中加载/ ProcessForm?email = testing来测试它,并查看一些输出.一旦你顺利完成,那么你就可以开始担心前端代码了.

希望这有助于您入门.