JQueryCode 404 status - how to get jqXhr url?

I have a jquery ajax statuscode function to handle 404 ... another answer claims that in the success method this.url gives the url for the request ... however this does not seem to be for my statusCode handler. Any ideas? Nothing I can see in the documentation on how to get the url for the request.

My ajax options object looks something like this (maybe I missed the bracket when I cut out code that wasn’t related 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; } } } } 
+6
source share
2 answers

The default context for AJAX event handlers (i.e. the object bound to this in the handlers) does provide the url property because it is a combination between $.ajaxSettings and the arguments passed in $. Ajax () .

However, in your case, you override this default context by passing $(this) in the context option. Moreover, doing this in ajaxOptions means that it will not be easy to extend this object with the current URL.

I would suggest linking the URL to the element that your plugin increments before calling AJAX, using data () or similar.

+8
source

You can change the request and settings objects before sending with the following code:

 $.ajaxSetup({ beforeSend: function(jqXHR, settings) { jqXHR.url = settings.url; } }); 

Then open xhr.url in the statusCode . It should work.

+30
source

Source: https://habr.com/ru/post/920397/


All Articles