how does long polling work javascript?

前端 未结 7 1211
傲寒
傲寒 2020-12-08 11:41

Hi I understand that in long polling you keep the connection with the server open for long till you a get a response back from the server and then poll again and wait for th

7条回答
  •  囚心锁ツ
    2020-12-08 12:02

    I was looking to do something with staggered data results where some would come back right away but the last few results might come back 10-15 seconds later. I created a quick little jQuery hack but it's kinda doing what I want (still not sure if it makes sense to use it tho):

    (function($) {
        if (typeof $ !== 'function') return;
        $.longPull = function(args) {
            var opts = $.extend({ method:'GET', onupdate:null, onerror:null, delimiter:'\n', timeout:0}, args || {});
            opts.index = 0;
            var req = $.ajaxSettings.xhr();
            req.open(opts.method, opts.url, true);
            req.timeout = opts.timeout;
            req.onabort = opts.onabort || null;
            req.onerror = opts.onerror || null;
            req.onloadstart = opts.onloadstart || null;
            req.onloadend = opts.onloadend || null;
            req.ontimeout = opts.ontimeout || null;
            req.onprogress = function(e) {
                try {
                    var a = new String(e.srcElement.response).split(opts.delimiter);
                    for(var i=opts.index; i

    Largely untested but it seemed to do what you had in mind. I can think of all sorts of ways it could go wrong, though ;-)

    $.longPull({ url: 'http://localhost:61873/Test', onupdate: function(data) { console.log(data); }});
    

提交回复
热议问题