javascript - 这个跨域ajax请求是如何工作的?

标签 javascript ajax xmlhttprequest cross-domain

我正在查看 this问题,其中有指向 http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/ 的链接其中有以下代码:

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);

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

最佳答案

服务器响应 Access-Control-Allow-Origin 设置为允许跨域请求

Response Headers
Access-Control-Allow-Origin: *  
Cache-Control   max-age=604800
Connection  keep-alive
Content-Length  494
Content-Type    application/json

http://www.w3.org/TR/cors/#access-control-allow-origin-response-hea

http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors

关于javascript - 这个跨域ajax请求是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775407/

相关文章:

javascript - 使用ajax追加时如何循环奇数和偶数?

javascript - 使用 XHR 请求加载图像

javascript - ES15 导入一个库作为另一个库的插件

javascript - 使用 javascript 时如何保护本地 API URL

javascript - 在js中将多维json转换为数组

Javascript (jQuery) 模块/库加载

javascript - 浏览器如何知道加载进度?

JavaScript 不适用于高于 Chrome mobile 45 的版本

javascript - Modernizr yepnope 条件回调仅在 false 时

javascript - Flot:可悬停的 x 轴标记