JavaScript跨域中的Flickr JSON返回错误 [英] Flickr JSON returning error in JavaScript cross domain
问题描述
我有这段代码,我试图返回Flickr API,但是出现以下错误.
I have this code and I'm trying to return Flickr API, however I get the following error.
跨源请求被阻止:同源策略禁止阅读 位于的远程资源
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback={callback}&tags=london&tagmode=any&format=json
. 可以通过将资源移到相同的域来解决此问题,或者 启用CORS.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback={callback}&tags=london&tagmode=any&format=json
. This can be fixed by moving the resource to the same domain or enabling CORS.
如何在我的代码中启用它?
How do I enable this in my code?
enter
MyFeed.prototype.getFeed = function(data) {
console.log(f.feedUrl);
var request = new XMLHttpRequest();
request.open('GET', f.feedUrl, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
console.log(request.responseText);
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
console.log("error");
}
};
request.onerror = function () {
// There was a connection error of some sort
};
request.send();
}here
推荐答案
由于使用的是 JSONP ,则不使用XMLHttpRequest
来检索资源,而是使用适当的src URL注入script
元素,并定义一个具有相同名称的函数,该函数将分配给jsoncallback
参数,脚本加载后即会调用该函数:
Since this is using JSONP, you don't use XMLHttpRequest
to retrieve the resource, you inject a script
element with appropriate src URL, and define a function with the same name assigned to jsoncallback
parameter which will be called once the script has loaded:
function handleTheResponse(jsonData) {
console.log(jsonData);
}
// ... elsewhere in your code
var script = document.createElement("script");
script.src = f.feedUrl;
document.head.appendChild(script);
只需确保您具有jsoncallback=handleTheResponse
(或任何您称呼的方法),并确保该方法可全局访问,那么您就可以使用了.
Just make sure you have jsoncallback=handleTheResponse
(or whatever you call your method), ensure the method is globally accessible, and you should be good to go.
这是一个演示:
function handleTheResponse(data) {
document.getElementById("response").textContent = JSON.stringify(data,null,2);
}
var script = document.createElement("script");
script.src = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=handleTheResponse&tags=london&tagmode=any&format=json"
document.head.appendChild(script);
<pre id="response">Loading...</pre>
这篇关于JavaScript跨域中的Flickr JSON返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!