简体   繁体   中英

HTTP Long polling based with Ajax

I am following an online example to do HTTP long polling. I am trying to do it without KnockoutJS.

Here is what I have on Javascript:

$(document.ready(function(){ 
   $("#mybutton").click(function() {
       //Some checks
       pollForMessages();
   }

   function pollForMessages()
   {
       $.ajax({
           url: '......', 
           type:"GET", 
           cache: false, 
           success: function(m) {/*....*/}, 
           error: function(h){/*......*/},
           complete: pollforMessages
       });
   }
}

But I am getting an Ajax error: $.ajax.error . If I follow the that example on github and use ko.applyBinding() and go that route it works. Whats the difference between this way and knockout in terms of the ajax long polling?

Knockout has nothing to do with long polling, xhr, ajax or whatever.

My two cents it is an issue with the scope of "this". The example uses quite an "excotic" solutions. I would never put the xhr object in an observable. It does not make sense doing that.

A StackTrace or a screenshot from chrome console would help.

Your code should work, see this fiddle http://jsfiddle.net/L8su2/886/

var data = {
    json: $.toJSON({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
    }),
    delay: 3
}
$(document).ready(function () {
    $("#mybutton").click(function () {
        //Some checks
        alert('start');
        pollForMessages();
    });

    function pollForMessages() {
        alert('poll');
        $.ajax({
            url: "/echo/json/",
            data: data,
            type: "POST",
            success: function (response) {
                console.log(response);
            },
            complete: pollForMessages
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM