开发者

Having trouble getting jQuery AJAX response headers

开发者 https://www.devze.com 2023-03-17 00:44 出处:网络
This is what I\'m trying: $.ajax({ type: \'GET\', url: \'http://imgur.com/upload/\', data: { url: \'http://upload.wikimedia.org/wikipedia/commons/3/3e/Phalaenopsis_JPEG.png\'

This is what I'm trying:

$.ajax({
  type: 'GET',
  url: 'http://imgur.com/upload/',
  data: {
    url: 'http://upload.wikimedia.org/wikipedia/commons/3/3e/Phalaenopsis_JPEG.png'
  },
  complete: function(jqXHR, textStatus) {
    console.log(jqXHR.getAllResponseHeaders());
  }
});

I just get an empty string.

Any help would be appreciated.

Edit:

These are the response headers I can see in Firebug:

Server: nginx
Date: Sat, 02 Jul 2011 03:04:26 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Set-Cookie: IMGURSESSION=asdfasdfasdfasdf; path=/; domain=.imgur.com
SERVERID=www4; pat开发者_运维问答h=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: http://imgur.com/ocuVX
Content-Encoding: gzip
Vary: Accept-Encoding


I've found one solution here: https://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/

function upload(url) {
  // Let's build a FormData object

  var fd = new FormData();
  fd.append("image", url); // Append the file
  fd.append("key", "6528448c258cff474ca9701c5bab6927");
  // Get your own key: http://api.imgur.com/

  // Create the XHR (Cross-Domain XHR FTW!!!)
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
  xhr.onload = function() {
    // Big win!
    // The URL of the image is:
    JSON.parse(xhr.responseText).upload.links.imgur_page;
   }
   // Ok, I don't handle the errors. An exercice for the reader.
   // And now, we send the formdata
   xhr.send(fd);
 }

Obviously this solution requires a POST which means you need to use an API key. I couldn't find any way of getting a response with the API-keyless GET method.

The only way I could manage to do an upload without an API key was to go through YQL and get the final redirect URL from the diagnostics:

urlToImgur = (url, callback) ->
  upload_url = "http://api.imgur.com/2/upload?url=#{url}"
  $.ajax
    url: 'http://query.yahooapis.com/v1/public/yql'
    dataType: 'jsonp'
    data:
      q: "select none from html where url='#{upload_url}'"
      diagnostics: true
    success: (data) ->
      redirects = data.query.diagnostics.redirect
      image_url = redirects[redirects.length-1].content
      callback image_url


Is it JSONP call? You won't get any headers then. Also see this: jqXHR.getAllResponseHeaders() won't return all headers


Make sure you're using > jQuery 1.5 and make sure you add crossDomain:true to your ajax attributes

0

精彩评论

暂无评论...
验证码 换一张
取 消