Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple json requests without conflict

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.

like image 651
Kris Hollenbeck Avatar asked Oct 20 '25 02:10

Kris Hollenbeck


1 Answers

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...

like image 156
Amith George Avatar answered Oct 21 '25 15:10

Amith George