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>
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();
});