Origin null is not allowed by Access-Control-Allow-Origin [duplicate]
Possible Duplicate:
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();
I am trying Ajax request to get data from the following Url. I go error:
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.
You're requesting from a different origin, you have to use JSONP. JSONP allows you to pass the response from the server to a callback function in javascript. The easiest way is to use jQuery and use the getJson() or ajax() methods, it'll allow you to do something like this:
$.getJSON('http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789',
yourCallback);
This has been asked and answered a zillion times. See here for one of those answers: JSON crossdomain communication with PHP file and a local javascript file. The Google search phrase you want is "same origin policy" to find many other explanations.
Sounds like the webservice does not supports CORS which is needed to bypass the same origin policy.
The product wiki webservice api supports JSONP so you can use that.
It requires you to set the format=json
in the querystring. And it requires you to set a callback.
//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);
If you want to go simple and can use a library such as jQuery, it will handle setting the callback for you.
jQuery.getJSON(
"http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789&format=json",
{},
function(data){
console.log(data);
}
);
精彩评论