【问题标题】:Ajax call to servlet, get parameterAjax调用servlet,获取参数
【发布时间】:2017-01-17 10:16:04
【问题描述】:

我正在使用 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代码是请求参数的简单日志打印,但是返回值始终为null:

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

【问题讨论】:

  • 您使用$.post 的第二个示例应该可以工作。控制台有错误吗?
  • 您是否检查过您的 servlet 是否被调用?
  • 检查你的servlet是否支持HTTP POST。我的意思是你的 servlet 中有 doPost 吗?

标签: java jquery ajax servlets


【解决方案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"));
    }

}

【讨论】:

  • 也为我工作。谢谢!
【解决方案2】:
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()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 2015-07-04
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多