Chaining ajax requests with jQuery's deferred

后端 未结 7 2264
天涯浪人
天涯浪人 2021-02-19 19:46

I have a web app which must call the server multiple times. So far, I had a long nested callback chain; but I would like to use jQuery\'s when,then etc

7条回答
  •  执笔经年
    2021-02-19 20:22

    All three callbacks (the two with then and the one with done) are applied to the same request – the original when call. This is because then returns the same Deferred object, rather than a new one, so that you can add multiple event handlers.

    You need to use pipe instead.

    $
    .when ($.get('pages/run-tool.html'))
    .then (function (args)
    {
        // This works fine
        alert(args);
        $('#content').replaceWith (args);
        $('#progress-bar').progressbar ({value: 0});
    })
    .pipe (function() { 
        return $.get('pages/test.html'); // the return value creates a new Deferred object
    })
    .done (function(args)
    {
        alert (args);
    });
    

提交回复
热议问题