简体   繁体   中英

XMLHttpRequest HTTP Headers

I'm trying to make a little script to rehost pictures on the web on imgur.

This is called Image Sideloading and you only need to point the browser to http://api.imgur.com/2/upload?url= + Picture's Url

It doesn't return any XML or JSON response so I can't parse it to get the img URL.

But I think I found a way to do this but can't get it to work properly. Here's the code I'm using.

$(document).ready(function() {
    $("#button").click(function() {
        str = $("input").val().toString();
        link = "http://api.imgur.com/2/upload?url=" + str;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", link);
        xhr.send();
        var headers = xhr.getAllResponseHeaders().toLowerCase;
        alert(headers);

    });

});

And looking at Google Chrome's console these are the results generated after the script runs.

I am not allowed to post images yet so here's a link to the results: http://i.imgur.com/xCyIP.png

I need to somehow access that 4th response header because even though this method doesn't return any parsable XML or JSON response that link is the uploaded img's URL which is all I need.

So is there a way to access that info? Why is it cancelled?

Thanks everyone!

Well, the API must return something, else it is useless.

Actually, http://api.imgur.com/examples advises you to do something like:

var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
    var url = JSON.parse(xhr.responseText).upload.links.imgur_page;
    alert(url);
}
xhr.send();

Edit. OK, I got it. Normally, the above code should work, but I think imgur is facing a problem. I will report the bug.

While the bug is still there, here is a dirty solution to serve your needs:

var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
    html = xhr.responseText;
    alert(html.substr(html.indexOf('http://i.imgur.com/') + 19, 5));
}
xhr.send();

You code wasn't working because you weren't waiting for the answer. You have to catch it through a callback function.

Edit. The above code only works locally. As you're using jQuery, let me introduce the shortcut $.post :

$(document).ready(function() {
    $("#button").click(function() {
        $.post('http://api.imgur.com/2/upload.json', {
            key: 'ec575de603b936e54c2b4a9f232d537e',
            image: $("input").val().toString()
        }, function(data) {
            alert(data.upload.image.hash);
        });
    });
});​

http://jsfiddle.net/Le_Sphinx/rEfdS/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM