Access-Control-Allow-Origin不允许使用null

时间:2011-09-20 03:44:15

标签: javascript ajax

  

可能重复:
  JSON crossdomain communication with PHP file and a local javascript file

var xhr = new XMLHttpRequest();
xhr.open("GET","http://api.productwiki.com/connect/api.aspxop=search&q=iphone&format=json&ke y=123456789");
xhr.onreadystatechange = function (){
    if(xhr.readyState=== 4 && xhr.status==200){
        console.log(xhr.responseText);
    }
}
xhr.send();

我正在尝试从以下Url获取数据的Ajax请求。我去了错误:

XMLHttpRequest cannot load http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789. Origin null is not allowed by Access-Control-Allow-Origin.

3 个答案:

答案 0 :(得分:0)

您从不同的来源请求,您必须使用JSONP。 JSONP允许您将响应从服务器传递到javascript中的回调函数。最简单的方法是使用jQuery并使用getJson()或ajax()方法,它允许你做这样的事情:

$.getJSON('http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789',
      yourCallback);

答案 1 :(得分:0)

这已被提出并回答了无数次。请参阅此处获取其中一个答案:JSON crossdomain communication with PHP file and a local javascript file。您想要的Google搜索词组是“相同的原始政策”,可以找到许多其他解释。

答案 2 :(得分:0)

听起来网络服务不支持绕过CORS所需的same origin policy

产品wiki webservice api支持JSONP,因此您可以使用它。

它要求您在查询字符串中设置format=json。它需要你设置一个回调。

//callback function
function YourGlobalFunction( data ){
    console.log(data);

}

//Fetch the content with JSONP
var scr = document.createElement("script");
scr.src = "http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789&format=json&callback=YourGlobalFunction";
document.body.appendChild(scr);

如果您想要简单并且可以使用jQuery等库,它将处理为您设置回调。

jQuery.getJSON(
    "http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789&format=json",
    {}, 
    function(data){ 
        console.log(data);
    }
); 
相关问题