我通过jQuery将一些参数从HTML表单发送到servlet,以进行MySQL查询,这样就可以了。如果我想在通过jsp之前通过jQuery截取一个会话属性(而不是DOM一个),它将失败。将 this.responseText 与slice()一起放在jQuery / jScript 中可能有效,但是文本太大且笨拙,无法处理,因此无法提示和停止在初始HTML文件中。
目前我有一种解决方法:在servlet中设置属性pAlert (具有两个可能的值-选择确定/错误选择),将其捕获到jsp文件(在隐藏元素内部)并通过调用DOM元素事件进行处理(如下面的代码所示),如果选择错误,则带有promt。但是,它应该是一个更简单的解决方案,其promt是由jQuery在初始HTML内触发的,而不是jsp文件触发的。这个问题看似是一个老问题,但我仍未找到答案。任何建议将不胜感激。我说得很详细,因为问题可能看起来很老。先感谢您!
jQuery代码:
$(document).ready(function () {
$('#refreshButton')
.click(function () {
var value1 = document.getElementById("idsectiune").value;
var value2 = document.formular.CuAl.value;
var value3 = document.getElementById("idizol").value;
var http = new XMLHttpRequest();
var url = "Sp";
type = "text";
var params = "var1=" + value1 + "&var2=" + value2 + "&var3=" + value3;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
window.location = "index.jsp";
} else {
var v3 = "${sessionScope.promt}";
alert(v3);
}
};
http.send(params);
});
});
Servlet代码设置属性:
List<Cond> ls = null;
ls = DBAccess.getQuery(strQuery, strWhereQry);
int i = 0;
String promt;
if (ls.get(0).getId() != 0) {
int ix = 1;
..........
promt = "Good selection!";
session.setAttribute("pAlert", "0");
} else {
promt = "Wrong selection!";
session.setAttribute("pAlert", "1");
}
session.setAttribute("sp", ls);
session.setAttribute("promt", promt);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
jsp文件
function alertare() {
var v = document.getElementById("idpAlert").value;
if (v === "1") {
var rasp = confirm("You must go back: select again!");
if (rasp)
window.location = "index.html";
else
document.getElementById("idTest").value = "0";
}
}
function tempAlert() {
if (document.getElementById("idTest").value === "0") {
document.getElementById("idTest").value = "1";
setTimeout(alertare, 3000);
}
}
<div onmouseover="tempAlert()">
答案 0 :(得分:0)
好吧,我找到了一种答案:它不是带有会话属性的,而是带有“响应”的。另一个重要的问题是相关的servlet路径未到达“ rd.forward(request,response);”代码。
在伺服器中:
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(promt);
HTML文件中的将jQuery更改为以下形式:
$(document).ready(function () {
$('#refreshButton').click(function () {
var value1 = document.formular.sect.value;
var value2 = document.formular.CuAl.value;
var value3 = document.formular.izol.value;
var http = new XMLHttpRequest();
var url = "Sp";
type = "text";
$.ajax({
type: "POST",
url: url,
data: ({var1: value1, var2: value2, var3: value3}),
success: function (data) {
var v = data.charAt(1, 1);
if (v === "=") {
alert(data);
} else
window.location = "index.jsp";
}
});
});
});