简体   繁体   中英

Unable to send Json data from Ajax to Servlet

I'm trying to send JSON data from a JavaScript function using Ajax to a Servlet.

Client side:

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);
}

Output from stringyfied data is {"aa":"aa","bb":"bb"} .

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    log(request.getParameter("aa"));
    log(request.getParameter("bb"));
}

Output in the logger is null and null .

Looks like JavaScript does not send data to the servlet, also if it's stringifyed correctly. Anyone?

Your Json object is in the body of the request therefore you need to parse the InputStream . Try this.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    JsonObject object = Json.createReader(req.getInputStream()).readObject();

    log(object.getString("aa"));
    log(object.getString("bb"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM