繁体   English   中英

JQuery Ajax POST 调用未正确发送参数

[英]JQuery Ajax POST call not sending parameters correctly

我正在尝试学习 Ajax,但在如何从客户端发送请求方面遇到了一些问题。

我在本地服务器上的“/web”上有一个处理请求的 jsp(不确定这是否是最佳实践,或者是否应该在 servlet 中处理,但它只是一个模型,所以我想可以)。 jsp的代码是这样的:

<%!
int i;
public void jspInit() {    
    i = 0;
    System.out.println("Initialized");
}
%>
<html> 
    <head>
        <title>My web page</title>
    </head>
    <body>
        <%
            String content = request.getParameter("content");
            System.out.println("Processed " + content); i++; %>
        <%= "Hello World " + i %> 
        <br>
        You sent me the text: <%= content %>
    </body> 
</html>

在客户端发送请求的功能是:

$("#send").click(function(){
    sentData = {content: "Test data to send"};
        $.post({
            url: '/web',
            data: JSON.stringify(sentData),
            processData: false,
            contentType: "application/json; charset=UTF-8",
            success: function(data) {
            $("#form").html("Sent from client: " + sentData.content + "<br>" + "Recieved from server:<br>" + data);
        },
        error: function(data) {
            $("#form").html("Could not send message.");
        }
    });

然而,这给出了输出

Sent from client: Test data to send
Received from server:
Hello World 2 
You sent me the text: null

在客户端上,服务器上的 System.out.println 仅在发送请求时写入“Processed null”。 我想我在通过 JQuery 发送数据时做错了什么。

通过 URL 地址“[mydomain]/web/?content=Test+data+to+send”发送数据给出了预期的输出

Hello World 2 
You sent me the text: Test data to send

就像通过 Postman 之类的工具发送 POST 请求一样,所以我认为服务器端设置正确。 我在 JQuery 请求中做错了什么? 我还尝试了一些更简单的调用,如下所示:

$("#send").click(function() {
    sentData = {content: "Test data to send"};
    $.post({
        url: '/web',
        data: sentData,
        dataType: 'html',
        success: function(data) {
            $("#form").html("Sent from client: " + sentData.content + "<br>" + "Recieved from server:<br>" + data);
        },
        error: function(data) {
            $("#form").html("Could not send message.");
        }
    });
});

结果相同。

尝试发送对象而不是字符串:

...
data: {content: "Test data to send"},
dataType: 'json'
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM