I have found many similar issues to my problem. Maybe it is me me, but I am having a hard time finding a real clear answer as to why I can't do multiple json requests or why this wouldn't work.
Here is my jQuery code:
$.getJSON('http://api.espn.com/v1/sports/basketball/nba/teams/16/news?apikey=0001234', function(data) {
console.log(data.headlines);
});
$.getJSON('http://api.espn.com/v1/sports/football/nfl/teams/16/news?apikey=0001234', function(data) {
console.log(data.headlines);
});
And here is the error I receive in the console log.
XMLHttpRequest cannot load http://api.espn.com/v1/sports/football/nfl/teams/16/news?apikey=62t2h4tsdmhr2q7aynvjuv2s. Origin null is not allowed by Access-Control-Allow-Origin.
When I run one $.getJSON request by itself it works fine. So I am assuming it is because I am making multiple requests. I am just not sure how to write it in a way where they don't conflict with each other.Any help is appreciated. Thanks
EDIT
So I guess the question then.. Is it possible to do multiple request this way. Is there an issue with my code? Or is it most likely an issue with ESPN's API. I could try using yahoo api and see if I get the same result.
Can you fire two json requests one after the other?
Yes. They will not interfere with one another.
Will ESPN return data for both the requests?
Presently No. Your second request will be returned a 403 response. They might change that sometime, who knows...
Why am I getting the error Origin null is not allowed by Access-Control-Allow-Origin.
?
As you mentioned in the comments, your script was executing from a url that began with file://
. As mentioned in this answer
There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send Access-Control-Allow-Origin: * (which, if you were reaching Flickr via $.get, they must have been doing) while the other was to echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.
Once you host the file on some server, even localhost
, you shoudnt receive that error. As an alternative, you could try using a jsonp
request, if ESPN supports it.
Try this query,
$.getJSON('http://api.espn.com/v1/sports/football/nfl/teams/16/news?apikey=0001234&callback=?',
function(data) {
console.log(data.headlines);
});
Notice the &callback=?
at the end of the url...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With