Skip to content Skip to sidebar Skip to footer

Flickr Json Returning Error In Javascript Cross Domain

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 resour

Solution 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:

functionhandleTheResponse(jsonData) {
  console.log(jsonData);
}

// ... elsewhere in your codevar 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:

functionhandleTheResponse(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);
<preid="response">Loading...</pre>

Solution 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.

functionjsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        deletewindow[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);

functioncallback(data){
 console.log(data);  
}

Post a Comment for "Flickr Json Returning Error In Javascript Cross Domain"