Flickr JSON returning error in JavaScript cross domain

*爱你&永不变心* 提交于 2019-12-04 23:01:04

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>

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