【问题标题】:JQuery Ajax POST call not sending parameters correctlyJQuery Ajax POST 调用未正确发送参数
【发布时间】:2018-01-29 11:21:09
【问题描述】:

我正在尝试学习 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.");
        }
    });
});

结果相同。

【问题讨论】:

  • 您明确声明 contentType: "application/json" 但您正在发送一个字符串...
  • 我从未见过$.post 与完整的 jQuery ajax 对象一起用作参数,我在文档中也没有看到它。您是否尝试过改用$.ajax? ($.post 的参数语法应该是 $.post(url, {param, 'test'});
  • 我不是 PHP 开发人员,但这是获取请求正文的正确方法吗.. request.getParameter.. 这听起来像是用于查询参数。
  • 据我所知,您只需将data: JSON.stringify(sentData), 替换为data: sentData,
  • Kaddath: 将 post 调用更改为 $.post('/web', {content: "Test data to send"}) 对我也不起作用。不知道我错过了什么。

标签: javascript jquery json ajax jsp


【解决方案1】:

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

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

【讨论】:

  • 对我来说结果相同,可能与将数据作为参数而不是在 BODY 中接收有关?
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多