Y
Y
Yakov Kravtsov2018-11-19 09:15:19
JavaScript
Yakov Kravtsov, 2018-11-19 09:15:19

How to catch location header in jQuery Ajax request?

Good afternoon!

Tell me, please, is it possible in some way to get access to the headers, namely to Location, when making an AJAX request with JQuery?
The thing is that you need to make it so that if the request goes AJAX, you need to catch this Location and redirect the browser ( window.location ), and not perform the same AJAX, but using that method. And if it turned out that the request was made directly, through the browser, in fact, go to the same Location.

How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ihor Bratukh, 2018-11-19
@virus_forever

$.ajax({
    url: 'https://jsonplaceholder.typicode.com/users',
    method: 'GET',
    dataType: 'json',
    success: function (data, status, jqXHR) {
        console.log(jqXHR.getAllResponseHeaders()); 
        // или jqXHR.getResponseHeader('location') (если такой header есть) 
    }
});

// pragma: no-cache
// content-type: application/json; charset=utf-8
// cache-control: public, max-age=14400
// expires: Mon, 19 Nov 2018 11:10:53 GMT

A
Arman, 2018-11-19
@Arik

How is it like that?

$(document).ajaxComplete(function (event, xhr) {
    var url = xhr && xhr.getResponseHeader('location');
    if (url) {
        window.location.assign(url);
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question