[英]JQuery Ajax POST call not sending parameters correctly
I'm trying to learn Ajax and have some problem with how to send the request from the client.我正在尝试学习 Ajax,但在如何从客户端发送请求方面遇到了一些问题。
I have a jsp at "/web" on my local server that handles requests (Not sure if this is best practise, or if it should be handled in a servlet, but it's just a mockup so I guess it's ok).我在本地服务器上的“/web”上有一个处理请求的 jsp(不确定这是否是最佳实践,或者是否应该在 servlet 中处理,但它只是一个模型,所以我想可以)。 The code for the jsp is like this:
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>
and the function for sending the request on client side is:在客户端发送请求的功能是:
$("#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.");
}
});
This however gives the output然而,这给出了输出
Sent from client: Test data to send
Received from server:
Hello World 2
You sent me the text: null
on the client, and the System.out.println on the server only writes "Processed null" when the request is sent.在客户端上,服务器上的 System.out.println 仅在发送请求时写入“Processed null”。 I guess I am doing something wrong when sending the data through JQuery.
我想我在通过 JQuery 发送数据时做错了什么。
Sending the data through the URL address "[mydomain]/web/?content=Test+data+to+send" gives the expected output通过 URL 地址“[mydomain]/web/?content=Test+data+to+send”发送数据给出了预期的输出
Hello World 2
You sent me the text: Test data to send
as does sending a POST request through tools like Postman, so I imagine the server side is set up correctly.就像通过 Postman 之类的工具发送 POST 请求一样,所以我认为服务器端设置正确。 What am I doing wrong at the JQuery request?
我在 JQuery 请求中做错了什么? I have also tried some more simple calls like this:
我还尝试了一些更简单的调用,如下所示:
$("#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.");
}
});
});
with the same result.结果相同。
Try to send object instead of string:尝试发送对象而不是字符串:
...
data: {content: "Test data to send"},
dataType: 'json'
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.