0

I currently have a Javascript application that consists of three files:

index.html
app.js
input.json

The input.json file gets referenced several times by the app.js file, in order to render content into divs in the index.html file.

I want to make it so that loading my index.html at http://example.com/myapp can take an externall hosted JSON as the source for app.js to read, like myexample.com/myapp?myhost.com/files/input.json.

Can anybody advise me on how to get this working?

1 Answers1

0

For this to work, you need to enable CORS on myexample.com.

Assuming you are using jQuery. (Take a look at here if you don't want to use jQuery for ajax requests)

$.get('http://myexample.com/myapp?myhost.com/files/input.json')
.done(function(data) {
    // use external 'data' here.
})
.fail(function() {
    // handle error here
});
Community
  • 1
  • 1
Bulent Vural
  • 2,630
  • 1
  • 13
  • 18
  • Thanks! I a using jQuery. So I've got the idea here, but if myhost.com/files/input.json can be any URL, how do I refer to it as a variable? specifically ```$.get('http://myexample.com/myapp?', function(data) { // use external 'data' here. });``` I want to get any URL that's there. Then first check if it's a JSON and throw an error if not--OR, just throw the can't read error if trying to parse it as a JSON in the `// use external 'data' here.` part can't read it. – dharmabum28 Feb 05 '17 at 08:37
  • I edited my answer to show handling errors on $.get. You can apply extra checks in .done() if you need. For example checking if the 'data' object is valid. You can also use try/catch block to control exceptions. – Bulent Vural Feb 05 '17 at 11:07
  • I think the last piece here then is to get the url of the current page, and then pass it as a variable to $.get. Right? – dharmabum28 Feb 06 '17 at 14:35
  • If the data you are fetching is on the same domain with the current page, you don't need to pass the full URL. Just call $.get with /files/input.json. Also CORS is not needed in this case. If different, you don't need the URL of the current page, you can call $.get with http://www.otherdomain.com/files/data.json assuming the other domain has proper CORS setting. – Bulent Vural Feb 07 '17 at 06:08
  • Great, this answers everything for me. Thanks! – dharmabum28 Feb 07 '17 at 17:45