The weird behaviour you're seeing is a limitation of the console
, and actually nothing to do with your code.
The resolution of the properties of the object are deferred until you expand the Object
in the console
. By that time the AJAX request has completed and responseText
is available. However, the value of results[0].responseText
is resolved immediately as undefined
.
If you did:
$.when([$.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"a":12}'}
})]).done(function(results) {
console.log(JSON.stringify(results[0])); //object with a responseText attribute
console.log(results[0].responseText); //undefined !!!
})
You'll see:
{"readyState": 1}
undefined
Instead.
As to how to solve your problem; I've never known $.when()
to accept arrays, nor does the documentation say it does. Because of this, when()
seems to be executing the done()
immediately, as the array is not a deferred (per the docs):
If a single argument is passed to jQuery.when and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
Instead pass your AJAX request(s) as separate parameters, as shown in the docs:
$.when($.ajax('a'), $.ajax('b')).done(function (a, b) {
// a & b = [ "success", statusText, jqXHR ]
});
As such:
$.when($.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"a":12}'}
}), $.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"b":12}'}
})).done(function(a, b) {
console.log(a[2].responseText);
console.log(b[2].responseText);
});
There you get:
{"a": 12}
{"b": 12}
... and an updated fiddle: http://jsfiddle.net/39mHw/2/