Reputation: 39
I'm following a tutorial on using Ajax with JavaScript, and this was the code we're making:
$('document').ready(function(){
$.ajax({
url: "AwesomeText.html",
type: "GET",
datatype: "Html"
})
.done(Success)
});
function Success(result){
$("p").append(result);
}
I got how it worked but there is one thing that confused me. We made a Success function to append the requested HTML file to the paragraph in the page, and then we passed a parameter called result, so from what I understand I can name the parameter anything and pass it as an argument and it will work. I took out success and passed in x as an argument and it still worked..
so my question is how does JQuery know it should store the requested HTML document in this parameter we're creating in this function? what if I have other functions will Jquery store the requested file to every function in it's parameter? I don't get how JQuery knows.
Also, there is a .done function in there, is that the same function that's explained here: https://api.jquery.com/deferred.done/ why is it called deferred?
Upvotes: 1
Views: 214
Reputation: 86
Default .done() callbacks will have 3 arguments passed through so based on your need you can use any of them in your success function with your own name. three arguments passed are data, textStatus ,jqXHR
so your success function's first argument would be the response of the ajax call,i.e data recieved from the server, second argument would be the status and third argument would the the jqueryXmlHttpRequest object.
based on your need you can access these objects in the same order
Upvotes: 3
Reputation: 1120
url
to ajax it basically fetches that url and returns whatever it got at that url
, AwesomeText.html
in your case
and then it sends the content of that url to success
function as a first parametersuccess = Type: Function( Anything data, String textStatus, jqXHR jqXHR )
.done(fn)
method makes calling some method after the method on which .done was called [You can say Promise
] which makes synchronous callsYou can check following question for understanding the promises and .done() method
jQuery deferreds and promises - .then() vs .done()
Upvotes: 1
Reputation: 4182
The .done method accepts a "success" function as input.
Success: 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 the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.
So, the first argument (call it whatever - data / result / x / etc) will contain the reply of the server.
Source: http://api.jquery.com/jquery.ajax/
Upvotes: 0