I have a jquery ajax statuscode function to handle a 404... another Stack Overflow answer states that in the success method, this.url gives the url for the request... however, this doesn't seem to be the case for my statusCode handler. Any ideas? Nothing that I can see in documentation about how to get the url for the request.
My ajax option object looks roughly like this (may have missed off a brace when trimming out code not relevant to this question)
;(function($) {
var defaultSettings = {
// ... other plugin specific settings
ajaxOptions:
{
cache:false,
context:$(this),
statusCode: {
404:function(xhr) {
// this line... this.url is always undefined (so is xhr.url)
$('#body').append('<div class="errordisplay">Content not found' + (this.url?': ' + this.url:'') + '</div>');
// ... do other stuff
return false;
}
}
}
}
You could modify the request & settings objects before sending with following code:
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
jqXHR.url = settings.url;
}
});
Then access xhr.url
in the statusCode
callback. It should work.
The default context for AJAX event handlers (i.e. the object bound to this
in the handlers) indeed exposes an url
property because it is a mix between $.ajaxSettings
and the arguments passed to $.ajax().
However, in your case, you're overriding that default context by passing $(this)
in the context
option. Moreover, doing that in ajaxOptions
means it will not be easy to extend that object with the current URL.
I would suggest associating the URL with the element your plugin is enhancing before the AJAX call, using data() or similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With