Reputation: 485
var theRequest = $.ajax({
url: 'http://jsonplaceholder.typicode.com/posts/1',
method: 'GET',
}).done(function(data){
console.log(data);
console.log(theRequest.responseText);
});
Is my understanding correct that the data
that is passed in to the function within the .done()
method should be the jqXHR
object that is returned from the $.ajax()
request?
I thought the below code would work but it doesn't because data
does not have a responseText
property, which I thought it would because I thought it should be the jqXHR
object returned from the $.ajax()
request?
$.ajax({
url: 'http://jsonplaceholder.typicode.com/posts/1',
method: 'GET',
}).done(function(data){
console.log(data);
console.log(data.responseText);
});
Upvotes: 0
Views: 330
Reputation: 1075249
Is my understanding correct that the data that is passed in to the function within the .done() method should be the jqXHR object that is returned from the $.ajax() request?
No, data
will be the data returned by the request. From the documentation:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the
success
callback option, the.done()
method replaces the deprecatedjqXHR.success()
method. Refer todeferred.done()
for implementation details.
...which I'll grant is less than thorough. :-) But note the three arguments in the function signature shown: data
, textStatus
, and jqXHR
. These are the same as for the success
function if you use it in the options, so the documentation for them is useful:
Type:
Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The
data
returned from the server, formatted according to thedataType
parameter or thedataFilter
callback function, if specified; a string describing the status; and thejqXHR
(in jQuery 1.4.x, XMLHttpRequest) object.
Upvotes: 2
Reputation: 29683
If you see the .done
prototype, the 3rd parameter will be jqXHR
whereas first parameter will be data
returned as response.
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to
deferred.done()
for implementation details.
.done
is alternative for .success
as mentioned in the docs.
So you can fetch jqXHR
if you include it as 3rd parameter in .done
Upvotes: 1
Reputation: 782148
The .done()
method receives three arguments: data
, textStatus
, and jqXHR
. data
is the response from the AJAX request; if you use dataType: 'json'
, it will be the object that results from parsing the JSON.
The responseText
property is in the jqXHR
parameter. It should be:
.done(function(data, textStatus, jqXHR) {
console.log(data);
console.log(jqXHR.responseText);
});
The two log messages should be the same.
Upvotes: 3