获取jQuery AJAX响应头出现问题

3
这是我正在尝试的内容:
$.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());
  }
});

我只得到了一个空字符串。
任何帮助将不胜感激。
编辑:
这是我在Firebug中看到的响应标头:
服务器:nginx
日期:周六,2011年7月2日03:04:26 GMT
内容类型:text/html; charset=utf-8
传输编码:分块
连接:关闭
设置Cookie:IMGURSESSION=asdfasdfasdfasdf; path=/; domain=.imgur.com
SERVERID=www4; path=/
过期时间:Thu,19 Nov 1981 08:52:00 GMT
缓存控制:no-store,no-cache,must-revalidate,post-check=0,pre-check=0
Pragma:no-cache 位置:http://imgur.com/ocuVX
内容编码:gzip 变化:接受编码
3个回答

5
我在这里找到了一个解决方案:https://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/。该方案与IT技术有关,可将图片上传至服务器,并能够使用HTML标签。
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);
 }

显然,该解决方案需要使用POST方法,这意味着您需要使用API密钥。我找不到任何使用无API密钥的GET方法获取响应的方法。

我唯一能够在没有API密钥的情况下进行上传的方法是通过YQL,并从诊断中获取最终重定向URL:

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

2

不用担心。如果它是跨域的,它会自动转为JSONP。如果你能告诉我你具体想做什么,那么我可能可以更好地帮助你。 - Mrchief
哦,对了,我没意识到jQuery会自动处理那个。我想要做的只是向该URL发送一个GET请求,并带上url参数。然后我需要从响应头中获取"Location"。我已经将我得到的响应头添加到了我的问题中。 - Acorn
你是否在寻找一个纯客户端的解决方案?如果你通过服务器端代理路由你的跨域调用会更容易。此外,我在问题中没有看到你更新的头部信息,我有遗漏什么吗? - Mrchief
我想制作一个书签小程序,可以将位于特定URL的图像上传到图像主机。imgur提供了一个API,允许您直接从URL上传图像。问题是我无法访问它返回的URL。 - Acorn
那么你需要进行POST请求。请看这里,它可能会有所帮助:http://api.imgur.com/examples#uploading_js - Mrchief
@Mrchief,让我们在聊天室继续这个讨论:http://chat.stackoverflow.com/rooms/1075/discussion-between-acorn-and-mrchief - Acorn

0

请确保您正在使用 > jQuery 1.5,并确保将 crossDomain:true 添加到您的 ajax 属性中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接