繁体   English   中英

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

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

我正在尝试创建一个将字符串值发送到Java servlet的AJAX请求。

在AJAX代码中,我有:

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

在处理请求的Java Servlet中,我尝试使用request.getParameter("foo")尝试获取值“ bar”。 如何在Java servlet的.send方法中获取值?

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

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

要了解有关JavaScript xhttp方法的更多信息,请参考此链接

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

要了解有关HTTP方法的更多信息Http Methods

如果要发送GET请求,则必须将参数绑定到URL。 而且您不需要设置请求标头。

xhttp.open("GET", link + "?foo=bar&lorem=ipsum", true);
xhttp.send();

如果要发送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