javascript无法将Json数据从Ajax发送到Servlet
我试图使用Ajax将JSON数据从JavaScript函数发送到Servlet
客户端:
function addObject() {
var data = {
aa: "aa",
bb: "bb"
}
var string = JSON.stringify(data);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "GalleryAdd", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("Done");
}
};
console.log(string);
xhttp.send(string);
}
stringyfied数据的输出是{"aa":"aa","bb":"bb"}
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
log(request.getParameter("aa"));
log(request.getParameter("bb"));
}
记录器中的输出是null
和null
看起来JavaScript不会向servlet发送数据,如果字符串化正确的话。有人吗
# 1 楼答案
Json对象位于请求体中,因此需要解析
InputStream
。试试这个