我正在尝试学习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.");
}
});
});
具有相同的结果。
答案 0 :(得分:0)
尝试发送对象而不是字符串:
...
data: {content: "Test data to send"},
dataType: 'json'
...