【问题标题】:How to send a variable value using AJAX to java servlet? (no jQuery)如何使用 AJAX 将变量值发送到 java servlet? (没有 jQuery)
【发布时间】:2019-01-11 23:06:54
【问题描述】:

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

在我的 AJAX 代码中:

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

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

【问题讨论】:

标签: javascript java ajax tomcat servlets


【解决方案1】:
xhttp.open("GET", link+'?foo=bar&lorem=ipsum', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      如果您要发送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");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 2013-03-19
        • 2013-01-26
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        相关资源
        最近更新 更多