我有两个jsp页面。一个是UI,另一个是获得响应的jsp。
UICounter.jsp :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page</title>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "Control.jsp", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var gotCount = parseInt(xmlHttpRequest.responseText);
document.getElementById("counterLabel").innerHTML = gotCount;
} else {
alert("HTTP errorrr " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div id="counterLabel">0 </div>
<script type="text/javascript">makeRequest();</script>
</body>
</html>
Control.jsp中:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
if(session.getAttribute("counter") != null && !session.getAttribute("counter").toString().equals(""))
{
String stringStatus = session.getAttribute("counter").toString().trim();
int statusCounter = Integer.parseInt(stringStatus);
session.setAttribute("counter",String.valueOf(++statusCounter));
}else{
session.setAttribute("counter",String.valueOf(1));
out.print(session.getAttribute("counter"));
}
%>
</body>
</html>
我想进行ajax调用,直到满足条件(结果为100)。我已经尝试在ajax函数的结果中调用相同的函数(makeRequest()
),同时检查直到结果为100,但它不起作用。有人可以建议如何实现这一点,示例表示赞赏?如果需要进一步澄清,请告诉我。
答案 0 :(得分:1)
使用jquery并尝试类似
的内容function makeRequest() {
$.ajax({
type: "POST",
url: "Control.jsp",
success: function (data) {
if(<your condition>) {
setTimeout(makeRequest, 100);
}
},
error: function () {
// Hanld error
}
});
}
答案 1 :(得分:0)
使用 setInterval
function makeRequest(){
$.ajax({
url:"/xxx/xxx",
method: "GET",
dataType: "json",
success: function (data) {
//---
}
});
}
/**request all day */
makeRequest();
var timer = setInterval(function(){
console.log("ping..");
makeRequest();
},10000);
/** stop after 3 min or so, if required*/
setTimeout(function(){
//stop the timer
window.clearTimeout(timer);
},180000);
计时器对象将很方便,以便稍后停止循环,如图所示。