我有一个基于 HTTP servlet 的网络应用程序。 这是对我的 servlet 的 JS 请求:
$.ajax({
type: "POST",
url: url,
xhrFields: {
withCredentials: false
},
data:{
"action" : action_type,
"fingerprint" : fingerprint,
"user_id" : user_id,
},
success: function(data) {
alert('sdp inviato!');
},
// vvv---- This is the new bit
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error, status = " + textStatus + ", " +
"error thrown: " + errorThrown
);
}
});
这是我的 servlet 代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action= request.getParameter("action");
UtenteModel um= new UtenteModel();
SDPLineModel sdpmodel= new SDPLineModel();
if (action.equals("CheckFingerprint")) {
String fingerprint = (String) request.getParameter("fingerprint");
String user_id = request.getParameter("user_id");
SDPLines sdpline = sdpmodel.findFingerprintNew(fingerprint, user_id);
if (sdpline == null) {
String message = "Fingerprint non valida!";
System.out.println("Fingerprint not found! ");
}
else {
System.out.println("Fingerprint found! ");
}
}
我的问题是:任何人都可以向我展示一些修改我的 servlet 和 js 代码的示例,设置特定的响应数据(对于两种情况,找到或未找到指纹)以及如何通过 JS 代码成功检查其值:函数(数据)?
最佳答案
如果我很清楚你的问题是你想通过 JS 代码向客户端显示来自 servlet 的响应!你可以试试这个:
if (sdpline == null) {
String message = "Fingerprint non valida!";
response.getOutputStream().print(message);
}else {
String message = ""Fingerprint found! ""
response.getOutputStream().print(message);
}
现在,如果您的请求成功完成,您将在 AJAX 请求中收到该消息。
},
success: function(data) {
alert('message coming from your servlet is '+data);
//here data will contain one of the messages depending on the if statement
},
关于javascript - HTTP Servlet 设置数据响应并通过 Javascript 检查它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42651371/