Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法将Json数据从Ajax发送到Servlet_Javascript_Java_Servlets - Fatal编程技术网

Javascript 无法将Json数据从Ajax发送到Servlet

Javascript 无法将Json数据从Ajax发送到Servlet,javascript,java,servlets,Javascript,Java,Servlets,我试图使用Ajax将JSON数据从JavaScript函数发送到Servlet 客户端: function addObject() { var data = { aa: "aa", bb: "bb" } var string = JSON.stringify(data); var xhttp = new XMLHttpRequest(); xhttp.open("POST&q

我试图使用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发送数据,如果字符串化正确的话。有人吗?

您的Json对象位于请求主体中,因此您需要解析
InputStream
。试试这个

protectedvoiddopost(HttpServletRequest-req、HttpServletResponse-resp){
JsonObject object=Json.createReader(req.getInputStream()).readObject();
日志(object.getString(“aa”);
日志(object.getString(“bb”);
}