The task is standard, shopping cart on the site. Products are dynamically loaded. I want to make sure that when I click on the "Add to cart" button, two parameters are passed to the servlet (this is the id that I take from the button and the count, the quantity of goods). How to transfer them to the servlet? Which I would like to receive in a servlet through request.getParametr ("id");

var xhr = new XMLHttpRequest(); var send = "{\"id\":" + "\"" + id + "\"," + "\"count\":" + "\"" + count + "\"" + "}"; send = JSON.parse(send); function reqReadyStateChange() { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { var data = xhr.responseText; } else { } } } xhr.open("POST", srvUrl, true); xhr.onreadystatechange = reqReadyStateChange; xhr.send(send); } 

Tried it like this, but servlet returns null

    1 answer 1

    JSON should not be parsed when sending, but instead lead to the string "stringify", and you can also add to the MIME type header

     var send = JSON.stringify({ id, count }); var xhr = new XMLHttpRequest(); xhr.overrideMimeType("application/json"); xhr.open("POST", srvUrl, true); xhr.onreadystatechange = function () { /* some handler */ }; xhr.send(send); 
    • thanks, already figured it out. Just an ordinary string needed to be obtained using the construct. BufferedReader json = new BufferedReader (new InputStreamReader (request.getInputStream (), "UTF-8")); String line = null; String str = new String (); while ((line = json.readLine ())! = null) {str + = line; } And then disassemble it in GSON. - Alexey