简体   繁体   中英

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:

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")

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.

On my ajaxvalidator javascript file I wrote this:

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. Sending data in request body works for POST only. The request URL query string is the part after ? in request 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:

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.

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