[英]Java can not receive data from AJAX POST
I am a newbie of jquery. 我是jquery的新手。 I am testing a very simple example.
我正在测试一个非常简单的示例。 Server side (use java) receives data from client side, print it at console.
服务器端(使用Java)从客户端接收数据,然后在控制台上打印。 Then response to client side another string.
然后响应客户端另一字符串。
At client side, I use: 在客户端,我使用:
$.ajax({ type: "POST", url: "http://localhost:8080/", data: { Name: "sanmao", Password: "sanmaoword" }, contentType: "application/json; charset=utf-8", dataType: "jsonp", jsonp: "jsonpcallback", jsonpCallback: "bc", success: function(response) { alert(response[0].name + " " + response[1].name); //$("#msg").html(decodeURI(data)); }, error: function() { } );
At servcer side, I use: 在服务方,我使用:
InputStream is = exchange.getRequestBody();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String temp = "";
try {
// s = ArticleExtractor.INSTANCE.getText(in);
temp = in.readLine();
System.out.println("client request: " + temp);
} catch (IOException e) {
System.out.println("Processing failed");
}
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
OutputStream responseBody = exchange.getResponseBody();
String s = "bc([{\"lng\":\"" + lng1 + "\",\"lat\":\"" + lat1 + "\",\"name\":\"" + name1 + "\"},{\"lng\":\""
+ lng2 + "\",\"lat\":\"" + lat2 + "\",\"name\":\"" + name2 + "\"}])";
exchange.sendResponseHeaders(200, 0);
responseBody.write(s.getBytes());
responseBody.close();
But it does not work. 但这行不通。 If I remove the "data:..." and "contentType...".
如果删除“ data:...”和“ contentType ...”。 Client side can receive the response string.
客户端可以接收响应字符串。 But server side can not receive the inbound string.
但是服务器端无法接收入站字符串。
Can anybody tell me why? 谁能告诉我为什么?
jQuery can't create JSON for you. jQuery无法为您创建JSON。 You have to manually convert the object yourself.
您必须自己手动转换对象。 You can use
JSON.stringify
: 您可以使用
JSON.stringify
:
data: JSON.stringify({
Name: "sanmao",
Password: "sanmaoword"
}),
When you pass an object as the data without doing this, jQuery simply converts it to a list of key value pairs which is sent in the post (in format key1=val1&key2=val2...
instead of JSON). 当您将对象作为数据传递而无需执行此操作时,jQuery会将其简单地转换为键值对列表,并在帖子中发送(格式为
key1=val1&key2=val2...
而不是JSON)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.