我正在尝试从html文件到servlet类进行AJAX调用以传递变量但不获取任何输出。请检查下面的代码并建议应该进行的更改。
FrontPage.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function func() {
var build = document.getElementById('name').textContent;
$.ajax({
type : 'GET',
url : 'http://localhost:8081/Sample/TestServlet',
data : build,
success : function(data) {
alert("Success");
},
error : function() {
alert("Error");
}
});
}
</script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a id="name" href="#" onClick="func();">Build1</a>
</body>
</html>
这是 TestServlet.java 。这是尝试打印使用Ajax调用从javascript函数传递的变量:
package com.infy;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(request.getParameter("build"));
}
}
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" 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>Sample</display-name>
<welcome-file-list>
<welcome-file>FrontPage.html</welcome-file>
</welcome-file-list>
<servlet>
<description>Sample Servlet</description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.infy.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>
我想将构建变量发送到servlet类并从servlet类中打印出来但没有得到任何输出。请帮我解决这个问题。
答案 0 :(得分:2)
您正在将请求作为GET方法发送,并且您没有在url中传递变量。请先在servlet中打印构建值,然后检查它是否会进入servlet。
您应该将GET请求发送为: -
url : "/TestServlet?build="+build+",
type : "GET"
, 并注意URL。 在servlet站点中创建一个json对象。喜欢
JSONObject jsonObj = new JSONObject();
jsonObj.put("build", build);
试试并告诉我。