Flickr JSON returning error in JavaScript cross domain

烂漫一生 提交于 2019-12-22 01:41:20

问题


I have this code and I'm trying to return Flickr API, however I get the following error.

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

回答1:


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

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.

Here's a demo:

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>



回答2:


There are multiple ways to resolve it, a easy one would be using jQuery;

assuming callback in

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback={callback}&tags=london&tagmode=any&format=json

callback="jQuery111203062643037081828_1446872573181"

enter 
MyFeed.prototype.getFeed = function(data) {

   $.ajax({
     url: f.feedUrl,
     dataType : "jsonp",
     success: function(response) {
       console.log(response);
     },
     error: function (e) {   
       console.log(e);
     }
   });
}here

or if you want this without jQuery, which is same as what @daniel-flint recommended.

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' +  callbackName;
    document.body.appendChild(script);
}

jsonp('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=callback&tags=london&tagmode=any&format=json', callback);

function callback(data){
 console.log(data);  
}


来源:https://stackoverflow.com/questions/33423853/flickr-json-returning-error-in-javascript-cross-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!