Reputation: 866
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 Open Notify API.
The problem with other questions asked and things I found on the Internet don't help me because they're all about local JSON files!
I also tried jQuery but it didn't work. Anyways, when I looked at the syntax, the script 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!
Upvotes: 0
Views: 651
Reputation: 510
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 URL you mentioned 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 this JSON for the sake of the example:
$.getJSON(
"https://jsonplaceholder.typicode.com/todos/1",
function( data ) {
$('div#title span').html(data.title);
$('div#completed span').html(data.completed?'true':'false');
}
);
<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>
Upvotes: 1