JQuery AJAX Polling Syntax

让人想犯罪 __ 提交于 2019-12-05 19:23:58

As noted above in my edit I have found a solution in this blog post that roughly accomplishes what I am looking for. As it turns out, I really only want my request to fire once. However, in regards to an "infinite" polling routine, this does the job quite nicely.

(function poll() {
    setTimeout(function () {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://somewhere.com/rest/123',
            success: function (data) {
                MyNamespace.myFunction(data); //DO ANY PROCESS HERE
            },
            complete: poll
        });
    }, 5000);
})();

I would note, however, that this routine does not initialize its first poll until 5 seconds after it is executed. Simple piece of code though! Thanks much to the author.

Daniel Allen Langdon

The timeout setting tells jQuery how long it should wait for a response from the server before giving up.

function Poll2(){
    $.ajax({
        //Use an ABSOLUTE reference to your target webservice
        url: "https://example.com/Sandbox/bitest/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        success:processResult,
        timeout: 5000,
        contentType: "text/xml; charset=\"utf-8\"",
        async: true
    });
}

If you want it to keep trying every five seconds until success, you could do something like this:

function Poll2(){
    $.ajax({
        //Use an ABSOLUTE reference to your target webservice
        url: "https://example.com/Sandbox/bitest/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        success:processResult,
        complete: Poll2,
        timeout: 5000,
        contentType: "text/xml; charset=\"utf-8\"",
        async: true
        error: function(xhr) {
            setTimeout(Poll2, 5000);
        }
    });
}

You are surely right, to have created an infinite loop.

But you could just check, if the request has to be made again or not and if not, just process the data (if needed here) and return from the Poll2 function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!