mercredi 1 avril 2015

How to use ajax to set the src of an image?

I need to set some headers when getting an image. The img src attribute does not allow this, so I'm using an XHR request to get the image. However, when I set the src attribute on the img tag after that request completes, it looks like the request is triggered again. Is there a way to cache the image and not trigger the second request?


Sample Code:



$(document).ready(function() {
var url = 'http://ift.tt/1BXHBTR'
var file = $.get(url);
file.then(function(data) {
$('#foo').attr('src', url);
});
});


JS Fiddle: http://ift.tt/1bK99XE


Note: my question is not about how to set the appropriate headers in the xhr request. My question is how to not trigger another GET from the setting of the src attribute and use the response from the XHR to display the image.


Aucun commentaire:

Enregistrer un commentaire