[英]Ajax call to servlet, get parameter
我正在使用 AJAX 調用調用我的 Java Servlet,但我無法從請求中讀取輸入參數。 我嘗試了兩種方法,但沒有運氣:
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: id,
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
和:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
reqValue: id
}, function(responseText) {
// $('#welcometext').text(responseText);
alert("OK!!!");
});
我的 servlet 代碼是請求參數的簡單日志打印,但返回值始終為空:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);
我怎樣才能讓它工作?
我發現讓代碼工作的唯一方法是手動將參數添加到 servlet url,如http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1
我檢查了你的代碼。這是我的工作代碼。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var id;
function fun() {
alert("aaaa");
id = 1;
$.ajax({
type : "POST",
data : {
reqValue : id
},
url : "/WebProject/callAjax"
});
}
</script>
</head>
<body>
<button id="scan" onclick="fun()">Sacn</button>
</body>
</html>
//小服務程序
@WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("reqValue"));
}
}
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue : id},
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
您需要在 servlet 中覆蓋不同的方法。 它們是 doPost()、doGet()、service() 等。
我懷疑您正在使用 doGet() 方法,這就是為什么當您向 URL 添加參數時,您的 java 代碼正在工作,而在其他兩種情況下,當您使用type : "POST"
java 代碼無法從請求正文中讀取數據(在post方法數據將被添加到請求正文)。
我建議您使用doPost()
或service()
方法代替 doGet()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.