I am trying to create an AJAX request that sends a string value to a Java servlet.
In the AJAX code I had:
xhttp.open("GET", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("foo=bar&lorem=ipsum");
in the java servlet that handles the request i tried using request.getParameter("foo")
hoping to get the values "bar". How can I get the values within the .send method on the Java servlet?
xhttp.open("GET", link+'?foo=bar&lorem=ipsum', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
Problem is that You are sending parameters in the body for the Get request. One option is to use Post request and the other one is to send parameter in URL in case of GET request (This is the answer suggested by Bibek Khadka).
To know more information about JavaScript xhttp methods refer this link
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
To know more about the HTTP methods Http Methods
If you are sending a GET
request you have to bind parameters to the URL. And you don't need to set the request header.
xhttp.open("GET", link + "?foo=bar&lorem=ipsum", true);
xhttp.send();
If you are sending a POST
request you have to parse parameters and the values to the send()
function and set the request header.
xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("foo=bar&lorem=ipsum");
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.