我正在使用servlet和AJAX进行简单的登录应用程序。我很好奇为什么当我将async指定为true时多次触发AJAX调用。当async指定为false时,调用只进行一次。
样品:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form id="flogin" class="panel">
<section class="panel-head">
</section>
<section class="panel-body">
<input type="text" id="txt-username" class="textbox" placeholder="Usuario o email"/>
<input type="password" id="txt-password" class="textbox" placeholder="Contraseña"/>
<section class="form-action-group">
<button type="submit" id="btn-login" class="btn btn-primary">Ingresar</button>
</section>
</section>
</form>
<script src="assets/js/login.js"></script>
</body>
</html>
JavaScript源代码:
document.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("#flogin");
form.addEventListener("submit", handleLogin, true);
function handleLogin(e) {
e.preventDefault();
var txtUsername = document.querySelector("#txt-username");
var txtPassword = document.querySelector("#txt-password");
var userdata = '{"username":'+txtUsername.value+',"password":'+txtPassword.value+'}';
loginByAjax(userdata);
resetForm(form);
}
function loginByAjax(data) {
var message;
var request = new XMLHttpRequest();
request.open("POST", "LoginController", false);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if(request.readyState != 4 || request.status != 200) {
message = request.responseText;
} else {
message = request.responseText;
}
console.log(message);
};
request.send("userdata="+data);
}
}
和servlet:
package com.company.controllers;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.company.utils.JsonUtils;
@WebServlet(asyncSupported=true, urlPatterns={"/LoginController"})
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger("LoginLogger");
public LoginController() {
super();
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
String strJson = request.getParameter("userdata");
Map<String, Object> userData = JsonUtils.getMapFrom(strJson);
String username = (String) userData.get("username");
String password = (String) userData.get("password");
if(username.equals("Duke") && password.equals("Duke777")) {
writer.print("Usuario correctamente identificado");
} else {
writer.print("Usuario o contraseña incorrectas");
}
writer.flush();
writer.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
processRequest(request, response);
} catch(ServletException | IOException e) {
logger.warning(e.getLocalizedMessage());
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch(ServletException | IOException e) {
logger.warning(e.getLocalizedMessage());
}
}
}
异步AJAX呼叫图像:http://i.imgur.com/SbxUBsz.png
有人可以向我解释为什么会这样吗?
答案 0 :(得分:0)
真的是servlet没有被多次调用,当你进行异步调用时会发生什么,在ajax请求阶段会多次调用onreadystatechange,因为连接建立直到连接关闭,有4个ajax调用中的步骤,每个调用onreadystatechange,你可以知道request.readyState的步骤:
您可以在这些步骤中记录消息,您可以通过这种方式记录ajax调用结束时的消息。
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {//if finish the ajax call and the status is ok
message = request.responseText;
console.log(message);
};
console.message('Checking the progress of the ajax call: ' + request.readyState);
}
您可以在MDN XMLHttpRequest
中查看更多信息