Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  193] [ 1]  / answers: 1 / hits: 184820  / 12 Years ago, thu, november 22, 2012, 12:00:00

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.


More From » json

 Answers
4

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:




  1. Use $.get('your.json') or some other such AJAX method.

  2. Write a file that sets a global variable to your json. (seems hokey).

  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this 1997 mode)

  4. Consult a voodoo priest.



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.


[#81856] Tuesday, November 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;