使用XMLHttpRequest的Flickr API调用不起作用 [英] Flickr API call with XMLHttpRequest not working

查看:94
本文介绍了使用XMLHttpRequest的Flickr API调用不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Flickr 获取JSON结果列表,并且普通js XMLHttpRequest无法正常工作.

I am trying to get a list in JSON result from Flickr and plain js XMLHttpRequest not working.

这是一个没有回调且无法正常工作的ajax调用示例

Here is ajax call example with no callback and not working

var url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&nojsoncallback=1";

xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    console.log(xhr.status);
  console.log(xhr.readyState);
    if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        console.log(data);  
    }else {
       console.log("error"); 
    }
}
xhr.open("GET", url)
xhr.send();

我遇到了错误-

js:1从来源'null'访问位于'https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&nojsoncallback=1'的XMLHttpRequest具有已被CORS政策阻止:所请求的资源上没有"Access-Control-Allow-Origin"标头.

你能告诉我问题出在哪里吗?

could you tell me where is the problem?

推荐答案

Flickr API不支持CORS.不使用JSONP API,就无法从其他来源的网页中嵌入的JS直接访问它.

The Flickr API doesn't support CORS. There is no way to access it directly, from JS embedded in a webpage on a different origin, without using the JSONP API.

Flickr确实提供了XML版本(从URL中删除 format = json& callback =?)和纯JSON版本(使用 format = json& nojsoncallback = 1 ),但没有Flickr授予CORS的许可,您将无法直接访问它.您可以使用代理服务器(可以是与网页来源相同的代理服务器,也可以是将CORS插入响应中的代理服务器.)

Flickr does provide an XML version (remove format=json&callback=? from the URL) and a plain JSON version (use format=json&nojsoncallback=1) but without Flickr's granting permission with CORS you can't access it directly. You could use a proxy server (either one on the same origin as your webpage, or one which inserts CORS into the response).

所请求的资源上没有"Access-Control-Allow-Origin"标头.来源'null.jsbin.com';因此,不允许访问.但是为什么我的getJSON没有得到相同的错误

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null.jsbin.com'; is therefore not allowed access. But why I am not getting same error with getJSON

因为当URL中具有 callback =?时,jQuery使用JSONP技术而不是XMLHttpRequest.

Because jQuery uses the JSONP technique instead XMLHttpRequest when you have callback=? in the URL.

这篇关于使用XMLHttpRequest的Flickr API调用不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆