Reputation: 6338
I'm using an Ajax request to get data from my server. The data I get come from several places (urls). I need a way to distinguish between data that comes from one url and the data coming from another url. The request is like this:
function initRequest(url)
var request = $.ajax({
url: url,
contentType: 'application/json',
dataType: 'json',
type: "GET"
});
request.done(function(msg) {
//i need to know what was the url of this request
//request.url is undefined
}
}
How do I do this? I mention that I cannot use the data itself (msg) to know the source url.
Upvotes: 1
Views: 608
Reputation: 339796
If the .done
function is in the lexical scope of initRequest
, just access the url
parameter directly - it's still in scope.
Otherwise, so long as you haven't supplied an alternate context
setting in the $.ajax
call you can just access this.url
in the .done
callback - by default jQuery invokes all AJAX callbacks with the AJAX object (which happens to contain this property) as the context.
Upvotes: 1
Reputation: 7452
Since you can't modify the returned JSON, use the url of the ajax object inside the callback:
.done(function(msg) {
var url = this.url;
});
Upvotes: 1
Reputation: 388316
You can use the variable url
inside the done callback because it is a closure variable
function initRequest(url)
var request = $.ajax({
url: url,
contentType: 'application/json',
dataType: 'json',
type: "GET"
});
request.done(function(msg, status, xhr) {
//you can use url here because it is a closure function
alert(url)
}
}
Upvotes: 1