I have this JSON file I generate in the server I want to make accessible on the client as the page is viewable. Basically what I want to achieve is:
I have the following tag declared in my html document:
<script id="test" type="application/json" src="http://myresources/stuf.json">
The file referred in its source has JSON data. As I've seen, data has been downloaded, just like it happens with the scripts.
Now, how do I access it in Javascript? I've tried accessing the script tag, with and without jQuery, using a multitude of methods to try to get my JSON data, but somehow this doesn't work. Getting its innerHTML
would have worked had the json data been written inline in the script. Which it wasn't and isn't what I'm trying to achieve.
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
You can use JavaScript like... Just give the proper path of your json file... Simply getting the data and appending it to a div... Initially printing the length in alert. that abc.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
Use the fetch() Function to Load JSON Files in JavaScriptdata . This function is only suitable for working in the web-based environment as the fetch API works only in that environment. After reading the file, we parse the data using json() function and display it.
You can't load JSON like that, sorry.
I know you're thinking "why I can't I just use src
here? I've seen stuff like this...":
<script id="myJson" type="application/json"> { name: 'Foo' } </script> <script type="text/javascript"> $(function() { var x = JSON.parse($('#myJson').html()); alert(x.name); //Foo }); </script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
You have a short list of options to load your JSON from a remote file:
$.get('your.json')
or some other such AJAX method.Final point:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src="">
is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
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