
Question:
How do I read a JSON file that is hosted on another server? There is a site which hosts JSON data and I want to access it through JavaScript. The JSON data is on the <a href="http://api.open-notify.org/astros.json" rel="nofollow">Open Notify API</a>.
The problem with other questions asked and things I found on the Internet don't help me because they're all about <strong>local JSON files</strong>!
I also tried jQuery but it didn't work. Anyways, when I looked at the syntax, the <em>script</em> part of the function had to be a PHP script on the server. I put the JSON file in that spot but nothing happened. I used the $.get()
method.
I would really appreciate it if someone answered me.
Thanks!
Answer1:In pretty much the same manner you'd call a local JSON file, you can fetch the contents of an online JSON file from another URL.
That being said, you should keep in mind that the URL should provide cross-origin headers to allow your domain to request that resource.
The <a href="http://api.open-notify.org/astros.json" rel="nofollow">URL you mentioned</a> has those headers and you can use it. However, their web server doesn't support HTTPS so I can't use it as an example here, thus I will use <a href="https://jsonplaceholder.typicode.com/todos/1" rel="nofollow">this JSON</a> for the sake of the example:
<pre class="snippet-code-js lang-js prettyprint-override">$.getJSON(
"https://jsonplaceholder.typicode.com/todos/1",
function( data ) {
$('div#title span').html(data.title);
$('div#completed span').html(data.completed?'true':'false');
}
);
<pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='title'>Title: <span></span></div>
<div id='completed'>Completed: <span></span></div>
Answer2:You can't for security reasons, look up CORS or cross origin requests. The browser will only allow you to get a file if there is a header in there that allows * for all domains or specifically has the domain you are requesting from white listed.
You can make the request with a call from the PHP on your server.