jQuery,简单的轮询示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6835835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:26:44  来源:igfitidea点击:

jQuery, simple polling example

jquerypolling

提问by Mike

I'm learning jQuery, and I'm trying to find a simple code example that will poll an API for a condition. (ie, request a webpage every few seconds and process the results)

我正在学习 jQuery,并且我正在尝试找到一个简单的代码示例,该示例将轮询 API 以获取条件。(即,每隔几秒请求一个网页并处理结果)

I'm familiar with how to do AJAX in jQuery, I just can't seem to find the "proper" way of getting it to execute on a "timer".

我熟悉如何在 jQuery 中执行 AJAX,但我似乎无法找到让它在“计时器”上执行的“正确”方式。

回答by Johnny Craig

function doPoll(){
    $.post('ajax/test.html', function(data) {
        alert(data);  // process results here
        setTimeout(doPoll,5000);
    });
}

回答by chrisjleu

Here's a helpful article on long polling(long-held HTTP request) using jQuery. A code snippet derived from this article:

这是一篇关于使用 jQuery进行长轮询(长期保持的 HTTP 请求)的有用文章。源自本文的代码片段:

(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 2000
        })
    }, 5000);
})();

This will make the next request only after the ajax request has completed.

这只会在 ajax 请求完成后发出下一个请求。

A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.

在遵守等待/超时间隔之前,将在第一次调用时立即执行上述变体。

(function poll() {
    $.ajax({
        url: "/server/api/function",
        type: "GET",
        success: function(data) {
            console.log("polling");
        },
        dataType: "json",
        complete: setTimeout(function() {poll()}, 5000),
        timeout: 2000
    })
})();

回答by Boopathi Rajaa

From ES6,

从 ES6 开始,

var co = require('co');
var $ = require('jQuery');

// because jquery doesn't support Promises/A+ spec
function ajax(opts) {
  return new Promise(function(resolve, reject) {
    $.extend(opts, {
      success: resolve,
      error: reject
    });
    $.ajax(opts);
  }
}

var poll = function() {
  co(function *() {
    return yield ajax({
      url: '/my-api',
      type: 'json',
      method: 'post'
    });
  }).then(function(response) {
    console.log(response);
  }).catch(function(err) {
    console.log(err);
  });
};

setInterval(poll, 5000);
  • Doesn't use recursion (function stack is not affected).
  • Doesn't suffer where setTimeout-recursion needs to be tail-call optimized.
  • 不使用递归(函数堆栈不受影响)。
  • 在 setTimeout-recursion 需要尾调用优化的地方不会受到影响。

回答by genesis

function poll(){
    $("ajax.php", function(data){
        //do stuff  
    }); 
}

setInterval(function(){ poll(); }, 5000);

回答by PeeHaa

function make_call()
{
  // do the request

  setTimeout(function(){ 
    make_call();
  }, 5000);
}

$(document).ready(function() {
  make_call();
});

回答by nobar

jQuery.Deferred()can simplify management of asynchronous sequencing and error handling.

jQuery.Deferred()可以简化异步排序和错误处理的管理。

polling_active = true // set false to interrupt polling

function initiate_polling()
    {
    $.Deferred().resolve() // optional boilerplate providing the initial 'then()'
    .then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
    .then( () => $.get('/my-api') ) // initiate AJAX
    .then( response =>
        {
        if ( JSON.parse(response).my_result == my_target ) polling_active = false
        if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
        if ( polling_active ) initiate_polling() // iterative recursion
        })
    .fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
    }

This is an elegant approach, but there are some gotchas...

这是一种优雅的方法,但有一些问题......

  • If you don't want a then()to fall through immediately, the callback should return another thenableobject (probably another Deferred), which the sleep and ajax lines both do.
  • The others are too embarrassing to admit. :)
  • 如果您不希望 athen()立即失败,则回调应返回另一个thenable对象(可能是 another Deferred), sleep 和 ajax 行都这样做。
  • 其他人都不好意思承认。:)

回答by vaquar khan

(function poll() {
    setTimeout(function() {
        //
        var search = {}
        search["ssn"] = "831-33-6049";
        search["first"] = "Harve";
        search["last"] = "Veum";
        search["gender"] = "M";
        search["street"] = "5017 Ottis Tunnel Apt. 176";
        search["city"] = "Shamrock";
        search["state"] = "OK";
        search["zip"] = "74068";
        search["lat"] = "35.9124";
        search["long"] = "-96.578";
        search["city_pop"] = "111";
        search["job"] = "Higher education careers adviser";
        search["dob"] = "1995-08-14";
        search["acct_num"] = "11220423";
        search["profile"] = "millenials.json";
        search["transnum"] = "9999999";
        search["transdate"] = $("#datepicker").val();
        search["category"] = $("#category").val();
        search["amt"] = $("#amt").val();
        search["row_key"] = "831-33-6049_9999999";



        $.ajax({
            type : "POST",
            headers : {
                contentType : "application/json"
            },
            contentType : "application/json",
            url : "/stream_more",
            data : JSON.stringify(search),
            dataType : 'json',
            complete : poll,
            cache : false,
            timeout : 600000,
            success : function(data) {
                //
                //alert('jax')
                console.log("SUCCESS : ", data);
                //$("#btn-search").prop("disabled", false);
                // $('#feedback').html("");
                for (var i = 0; i < data.length; i++) {
                    //
                    $('#feedback').prepend(
                            '<tr><td>' + data[i].ssn + '</td><td>'
                                    + data[i].transdate + '</td><td>'
                                    + data[i].category + '</td><td>'
                                    + data[i].amt + '</td><td>'
                                    + data[i].purch_prob + '</td><td>'
                                    + data[i].offer + '</td></tr>').html();
                }

            },
            error : function(e) {
                //alert("error" + e);

                var json = "<h4>Ajax Response</h4><pre>" + e.responseText
                        + "</pre>";
                $('#feedback').html(json);

                console.log("ERROR : ", e);
                $("#btn-search").prop("disabled", false);

            }
        });

    }, 3000);
})();

回答by Sohan

I created a tiny JQuery plugin for this. You may try it:

我为此创建了一个很小的 ​​JQuery 插件。你可以试试:

$.poll('http://my/url', 100, (xhr, status, data) => {
    return data.hello === 'world';
})

https://www.npmjs.com/package/jquerypoll

https://www.npmjs.com/package/jquerypoll

回答by jozo

This solution:

这个解决方案:

  1. has timeout
  2. polling works also after error response
  1. 有超时
  2. 错误响应后轮询也有效

Minimum version of jQuery is 1.12

jQuery 的最低版本是 1.12

$(document).ready(function () {
  function poll () {
    $.get({
      url: '/api/stream/',
      success: function (data) {
        console.log(data)
      },
      timeout: 10000                    // == 10 seconds timeout
    }).always(function () {
      setTimeout(poll, 30000)           // == 30 seconds polling period
    })
  }

  // start polling
  poll()
})