【问题标题】:Panoramio API access using AJAX - error "Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin."使用 AJAX 访问 Panoramio API - 错误“Access-Control-Allow-Origin 不允许Origin hxxp://foo.bar。”
【发布时间】:2011-05-31 03:18:25
【问题描述】:

我目前遇到这个问题,想知道为什么...?

错误信息是:

"XMLHttpRequest 无法加载http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?. Access-Control-Allow-Origin 不允许来源 hxxp://foo.bar。 test_panoramio.html:59Uncaught SyntaxError: Unexpected token )"

“hxxp://foo.bar”指的是我运行脚本的站点。

网站上的“test_panoramio.html”包含例如以下:

var url = "http://www.panoramio.com/wapi/data/get_photos?    
v=1&key=dummykey&tag=test&offset=0&length=20&minx=-
30&miny=0&maxx=0&maxy=150&callback=?";

function myScriptFn()
 {
  if (window.XMLHttpRequest) {
   myAjax = new XMLHttpRequest();
  if ( typeof myAjax.overrideMimeType != 'undefined') {
  myAjax.overrideMimeType('text/xml');
 }
} else if (window.ActiveXObject) {
myAjax = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  alert('The browser does not support the AJAX XMLHttpRequest!!!');
}

myAjax.onreadystatechange = function() 
{
       handleResponse();
} 

myAjax.open('GET', url, true);
myAjax.send(null);

}

function handleResponse()
{
if (myAjax.readyState == 4){    // Response is COMPLETE
    if ((myAjax.status == 200) || (myAjax.status = 304))
    {
            // do something with the responseText or responseXML
             processResults();

     }else{
     alert("[handleResponse]: An error has occurred.");
     }
     }
}

function processResults()
{

 myObj = eval( '(' + myAjax.responseText + ')' );
 ...
 doSomething()
 ...
}

如果直接在浏览器中键入 Panoramio URL,则可以使用。

请你帮我解决这个问题,我已经没有希望了......:(

提前谢谢你,

你的 马尔科

【问题讨论】:

    标签: php javascript ajax api panoramio


    【解决方案1】:

    您要打的是the same origin policy,它可以防止通过 XMLHttpRequest 进行跨域请求。如果站点支持是(以及您尝试访问的支持!)JSONP,则有一种解决方法。这意味着您只需要一个 <script> 标记并填充该 callback 参数,如下所示:

    <script type="text/javascript" src="http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=myFunction"></script>
    

    还有一个同名的函数:

    function myFunction(data) {
      //data is what came back, it's a javascript object
    }
    

    You can test out a working example here.

    【讨论】:

    • 谢谢尼克!这解决了问题!而且,非常感谢您提供了实际展示它的示例。最好的问候,马尔科
    猜你喜欢
    • 2013-03-10
    • 2013-09-09
    • 2019-11-25
    • 2012-06-07
    • 2011-11-05
    相关资源
    最近更新 更多