【问题标题】:Calling ajax function continuously at a specific interval until a condition is met?以特定间隔连续调用ajax函数直到满足条件?
【发布时间】:2014-07-28 16:21:46
【问题描述】:

我有两个 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,但它不起作用。有人可以建议如何实现这一点,示例是否值得赞赏?如果需要进一步澄清,请告诉我。

【问题讨论】:

  • 为什么支持旧版IE xhr? xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest); 可能不会像您认为的那样做,为什么在您只想要数字时返回整个 HTML 文档(大概)???

标签: javascript ajax jsp


【解决方案1】:

使用 jquery 并尝试类似的方法

function makeRequest() {
    $.ajax({
        type: "POST",
        url: "Control.jsp",
        success: function (data) {
        if(<your condition>) {
          setTimeout(makeRequest, 100);
        } 
        },
        error: function () {
           // Hanld error
        }
    });
    }

【讨论】:

  • 我从 SO 聊天中得到了帮助,因为这很相似,所以我接受了。谢谢。
【解决方案2】:

使用 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);

timer 对象可以方便地稍后停止循环,如图所示。

【讨论】:

    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 2021-12-10
    • 2021-06-10
    • 2011-07-10
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多