如何使用Jquery/Javascript轮询WebMethod

本文关键字:轮询 WebMethod Javascript 何使用 Jquery | 更新日期: 2023-09-27 18:08:58

谁能告诉我如何轮询到webMethod在特定的间隔使用Javascript/JQuery ?我尝试setInterval &setTimeOut,但没有一个是为我工作。我的应用程序生成用户请求的报告。由于报告生成需要10-15分钟,我不想阻塞UI线程,所以我从javascript创建了一个reporttid按钮点击,并使用_dopostback调用按钮点击事件,并将reporttid传递给它。c#按钮点击事件调用generate_report()函数使用Delegate/BeginInvoke,现在我想轮询到我已经创建的WebMethod,以便获得报告…这是一个代码片段。

 $("#btn1").click(function () {
     var ReportID = generateReportID();
     __doPostBack("<%= btnGenerate.UniqueID %>", ReportID);
     IntervalID = setInterval(function () { Poll(ReportID); }, 30000);
 });
 function Poll(id) {
     $.ajax({
         type: "POST",
         url: "Default.aspx/WebMethod",
         data: "{'ReportID','" + id + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
                    // Check if report is ready 
                    // If not poll again after 30 secs
                    // If report is ready Get the Report and clearInterval
         },
         failure: function (error) {
         }
     });
 };
 [WebMethod]
 public static string WebMethod(string ReportID)
 {
     if (ResultSet.ContainsKey(int.Parse(ReportID)))
     {
         return "Ready";
     }
     else
     {
         return "NotReady";
     }
  }

所以On按钮单击我如何开始投票到这个web方法后,每30秒,直到报告是"准备好",并清除间隔后,一旦它准备好了。??

如何使用Jquery/Javascript轮询WebMethod

SetInterval工作正常,PostBack是罪魁祸首....随后的回发即按钮点击将杀死之前的setinterval ....所以现在我把所有的reportid传递给codebehind在按钮点击函数和setinterval使用客户端脚本

Page. clientscript . registerstartupscript (typeof(Page), "test" + UniqueID, "setInterval(function () {Poll(reporttid);}, 30000);", true);

可以选择将reporttid发送到函数后面的代码中,并使用客户端脚本循环并设置每个reporttid的间隔,还可以将reporttid保存在localStorage中,以便在随后的回发中可用。

注意:非常感谢你的帮助@Krzysztof Safjanowski

使用SetTimeout递归地调用自己,直到得到想要的结果。

,

function initPoll()
{
    setTimeout(pollWebServer(), 30000);
}    
function pollWebServer()
{
     if(!checkResult())
         setTimeout(pollWebServer(), 30000);
}    
function checkResult()
{
    //Do some work to check result that you are looking for
    //This is where you would check your Web Method using jQuery
    return false;
}