2

I have a script like this:

var img = $("<img />").attr('src', images[i]).load(function() {
      alert(this.src); // old url
})

Sometimes the server will throw a 301 Moved Permanently or 302 Moved Temporarily HTTP code, and the actual image loaded will differ. How can I:

  • detect if a redirection happened
  • find out the new url - this.src doesn't take the redirect into account
  • possibly prevent the new url from being loaded

?

[edit]
As per How to prevent ajax requests to follow redirects using jQuery, the last one is not possible. How can I find out the new URL?

Community
  • 1
  • 1
Robus
  • 8,067
  • 5
  • 47
  • 67
  • In which situation do you get a redirect? What does "sometimes" mean? Why don't you want to follow the redirect? –  Jun 06 '15 at 14:57
  • @LutzHorn Irrelevant magic behind the project, can't work around that – Robus Jun 06 '15 at 15:09
  • OK, but why don't you want to follow the redirect? –  Jun 06 '15 at 15:13
  • @LutzHorn The redirect always contains an error message, no need for it to be loaded. – Robus Jun 06 '15 at 15:15
  • A redirect is not an error, it is a redirect. It contains a `Location` header which IMO the client should follow. –  Jun 06 '15 at 15:18
  • @LutzHorn The page the `Location` points to is always an image with the text "An error occured". Hence there is no need to load it. – Robus Jun 06 '15 at 15:20

1 Answers1

0

You could try to get the status using an AJAX request, something like this:

var img =  new Image();
$(img).load(
'someimage.png', 
function(response, status, xhr) {
    if (xhr.status == 200) {
        $('#img').attr('src','someimage.png')
    } else {
        //do something with xhr.status
    }
});
Marcel Emblazoned
  • 593
  • 2
  • 4
  • 16