简体   繁体   English

使用Ajax从Servlet中的doGet获取参数

[英]Getting parameter from a doGet in Servlet using Ajax

I want to get the parameter from a input form which is set on my index.html: 我想从我的index.html上设置的输入表单中获取参数:

GET:<br> 
<input type="text" size="20" id="name2" onblur="validate2()"  
     onFocus = "document.getElementById('msg2').innerHTML = ' '">
<div id = "msg">&nbsp</div>

On my servlet I want to get this parameter by request.getparameter("name2") 在我的servlet上,我想通过request.getparameter(“name2”)获取此参数

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Get");
    System.out.println(request.getParameter("name2"));
    if(!request.getParameter("name2").equals("")) {
        numer = request.getParameter("name2");
        serviceConnection(request, response);
    }
}

but when I am starting my application the system.out.println is just printing the null variable. 但是当我启动我的应用程序时,system.out.println只是打印null变量。

On my ajaxvalidator javascript file I wrote this: 在我的ajaxvalidator javascript文件中我写了这个:

function validate2() {
var idField = document.getElementById("name2");
var data = "name2=" + encodeURIComponent(idField.value);
if (typeof XMLHttpRequest != "undefined") {
    req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("GET", url, true);
req.onreadystatechange = inserter2
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);

}

function inserter2() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var msg1 = req.responseText
            if (msg1 == "") {
                document.getElementById("msg").innerHTML = "<div style=\"color:red\">Wadliwa nazwa</div>";
                document.getElementById("org").value = '';
            } else {
                document.getElementById("org").value = msg1;
            }
        }
    }

How to solve this problem? 如何解决这个问题呢?

Your mistake is here: 你的错误在这里:

req.open("GET", url, true);
// ...
req.send(data);

In HTTP GET, the data needs to go in request URL query string, not in request body. 在HTTP GET中,数据需要进入请求URL查询字符串,而不是请求体。 Sending data in request body works for POST only. 在请求正文中发送数据仅适用于POST。 The request URL query string is the part after ? 请求URL查询字符串是后面的部分? in request URL. 在请求URL中。

So, this should do: 所以,这应该做:

req.open("GET", url + "?" + data, true);
// ...
req.send();

Note that you can remove the request body content type header. 请注意,您可以删除请求正文内容类型标头。

See also: 也可以看看:

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

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