2012-01-08 47 views
6

我看this问题和它给http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/一个链接,具有下面的代码:这个Cross Domain ajax请求如何工作?

var fd = new FormData(); 
fd.append("image", file); // 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); 

这是如何跨域请求工作?我认为通常有一些安全限制可以阻止人们这样做。

回答

1

Imgur实现跨来源资源共享(CORS) 。

CORS标准通过添加新的HTTP标头起作用,允许服务器 为允许的源域服务资源。浏览器支持这些 标题并强制执行它们建立的限制。此外,对于 可能导致对用户数据产生副作用的HTTP请求方法(特别是对于 ,对于GET以外的HTTP方法或对于某些MIME类型的 POST使用),规范要求浏览器 “预检”请求通过HTTP OPTIONS请求头从服务器 请求支持的方法,然后在从服务器“批准” 服务器时,使用实际HTTP请求 方法发送实际请求。服务器还可以通知客户端 (包括Cookie和HTTP验证数据)是否应该以 请求发送“凭证”。

查看http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/了解更多信息。