通过Ajax调用的轮询机制

Polling mechanism through an Ajax call

本文关键字:机制 Ajax 调用 通过      更新时间:2023-09-26

我需要添加轮询机制来通过我的网页调用web服务。为此,我尝试在javascript页面中使用ajax调用。我对ajaxjavascript很陌生。我写了下面的代码。

<html>
<head>
    <script language="JavaScript" type="text/javascript">
         function pollServerForNewMail() {
            setTimeout(function(){
            $.ajax({ url: "server", success: function(data){
                alert("TEST");
                poll();
            }, dataType: "json"});
        }, 10000);
</script>
</head>
<body>
</body>
</html>

我需要的是每10秒启动一次警报测试。任何人都请帮我。

我将用我的两个jsp文件编辑这篇文章。

index.jsp文件

<html>
    <table style="width:100%;text-align:center;'">
<tr>
<td style="text-align:center;width:100%">                               
<a href="polling.jsp?reset=true"><img src="images/import.png" /></a>
</td>
</tr>
</table>
</html>

polling.jsp文件

         <html>
            <head>
                <script language="JavaScript" type="text/javascript">
                     function pollServerForNewMail() {
                        setTimeout(function(){
                        $.ajax({ url: "server", success: function(data){
                            alert("TEST");
                            poll();
                        }, dataType: "json"});
                    }, 10000);
}
        pollServerForNewMail() ;  
          </script>
            </head>
            <body>
       </body>
        </html>

感谢

setTimeout将只触发一次计时器。

使用setInterval每X秒执行一次代码:

function pollServerForNewMail() {
    setInterval(function(){
        // Code in this function will run every 10 seconds
        $.ajax({ url: "server", success: function(data){
            alert("TEST");
            poll();
        }, dataType: "json"});
    }, 10000);
}

我通过如下更改polling.jsp文件解决了问题。我将添加我的解决方案。

  <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            var set_delay = 5000,
                    callout = function () {
                        $.ajax({
                            /* blah */
                        })
                                .done(function (response) {
                                   alert("TEST");
                                })
                                .always(function () {
                                    setTimeout(callout, set_delay);
                                });
                    };
            callout();
        </script>
    </head>
    <body>
    </body>
    </html>