سؤال

I've taken the sample code from the jquery deferred.then() documentation: Chain tasks.

The problem I found is with the chained.done handler that, from what I understand, should be called when all the requests are done. Instead the handler is executed when the first request is done, and it retrieves the payload from this same request.

This is the code that I'm using:

var request = $.ajax("http://www.json-generator.com/j/bPyGnSXXTm", {
    dataType: "json",
    crossDomain: true
}),
    chained = request.then(function (data) {
        console.log('First call, data:', data);
        $('body').append('<p>' + 'First call, data: ' + JSON.stringify(data) + '</p>');
        return $.ajax(data[0].url, {
            crossDomain: true
        });
    });

chained.done(function (data) {
    // data retrieved from url2 as provided by the first request
    console.log('Second call, data:', data);
    $('body').append('<p>' + 'Second call, data: ' + JSON.stringify(data) + '</p>');
});

You can find a jsfiddle here.

Furthermore you can open console and see that the handler is being executed before the second request, (Activate log XMLHttpRequests).

From my understanding the chained is getting the value of request, and not the returned value of the $.ajax as it should.

هل كانت مفيدة؟

المحلول

Using jQuery prior to 1.8, you need to use .pipe() instead of then():

chained = request.pipe(function (data) {...});

See DOC for change between version: http://api.jquery.com/deferred.then

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top