V
V
Viktoria Smirnova2018-04-17 12:46:35
Java
Viktoria Smirnova, 2018-04-17 12:46:35

How to format a response to an XMLHttpRequest Object?

Everywhere it is described in great detail how the XMLHttpRequest Object sends a request to the server and how it receives a response, but nowhere is it really covered how the server wraps up this “package”, so to speak, and sends it back?

The question is how does the Servlet return the response. It is necessary for me that the servlet would return the request worked out by my business to a DB, namely the table from a DB. Here's how it's done. The question is probably more for the Javasts.


Request XMLHttpRequest

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = "Hello";
    }
};
xhttp.open("POST", 'Servlet', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("val="+ val);
<p id="demo"></p>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-04-17
@Vika7

private ResultSet fetchRows() {
    ...
}

private JSONObject toJson(ResultSet rows) {
    ...
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.append(toJson(fetchRows()));
    }
}

<div id="output"></div>
<button id="button">Нажми меня</button>

var output = document.getElementById('output');
var button = document.getElementById('button');

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState != 4) return;

    if (xhr.status == 200) {
        data = JSON.parse(xhr.responseText);
        response = ['<table>', '<tr><th>Имя</th><th>Фамилия</th></tr>'];
        for (var x = 0; x < data.persons.length; x++) {
            response.push('<tr>');
            response.push('<td>' + data.persons[x].firstName + '</td>');
            response.push('<td>' + data.persons[x].lastName + '</td>');
            response.push('</tr>');
        }
        response.push('</table>');
        output.innerHTML = response.join('');
    }
    else {
        alert('Ошибка! ' + xhr.statusText);
    }
    
    button.innerHTML = 'Нажми меня';
    button.disabled = false;
};

button.addEventListener('click', function(event) {
    this.innerHTML = 'Загружаю...';
    this.disabled = true;
    
    xhr.open('POST', '/some/servlet/url', true);
    xhr.send();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question