简体   繁体   English

如何使用AJAX将变量值发送到Java Servlet? (没有jQuery)

[英]How to send a variable value using AJAX to java servlet? (no jQuery)

I am trying to create an AJAX request that sends a string value to a Java servlet. 我正在尝试创建一个将字符串值发送到Java servlet的AJAX请求。

In the AJAX code I had: 在AJAX代码中,我有:

    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". 在处理请求的Java Servlet中,我尝试使用request.getParameter("foo")尝试获取值“ bar”。 How can I get the values within the .send method on the Java servlet? 如何在Java servlet的.send方法中获取值?

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. 问题在于您正在正文中为Get请求发送参数。 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). 一种选择是使用Post请求,另一种是在GET请求的情况下在URL中发送参数(这是Bibek Khadka提出的答案)。

To know more information about JavaScript xhttp methods refer this link 要了解有关JavaScript xhttp方法的更多信息,请参考此链接

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

To know more about the HTTP methods Http Methods 要了解有关HTTP方法的更多信息Http Methods

If you are sending a GET request you have to bind parameters to the URL. 如果要发送GET请求,则必须将参数绑定到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. 如果要发送POST请求,则必须解析参数和值到send()函数并设置请求标头。

xhttp.open("POST", link, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("foo=bar&lorem=ipsum");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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