Dynamically load JSON

A

amcallis01

I'm trying to load JSON data using this (well published...) code in my
html head tag:

<script type="text/javascript">
var e = document.createElement('script');
e.setAttribute("type", "text/javascript");
e.setAttribute("src", "jsonData.txt");
document.getElementsByTagName("head")[0].appendChild(e);
</script>

The contents of jsonData.txt looks like:
var json;
json=[{"id":"20226 Pioneer Blvd, Cerritos, CA
","lat":"33.846611","lng":"-118.081933"},{"id":"7565 Carson Blvd, Long
Beach, CA ","lat":"33.825825","lng":"-118.085297"}];

When I try to access the variable "json", IE6 and IE7 tell me that
json is undefined. However "json" is defined when using FF2.

Mysteriously, if I put "alert('hi');" just before my </script> tag,
"json" *does* get defined in IE6&7. Not sure why that would be.

Any suggestions on how to load this JSON data across these 3
browsers? I would prefer to stick with this general method (vs. AJAX)
if possible.
 
M

Martin Honnen

I'm trying to load JSON data using this (well published...) code in my
html head tag:

<script type="text/javascript">
var e = document.createElement('script');
e.setAttribute("type", "text/javascript");
e.setAttribute("src", "jsonData.txt");
document.getElementsByTagName("head")[0].appendChild(e);
</script>

The contents of jsonData.txt looks like:
var json;
json=[{"id":"20226 Pioneer Blvd, Cerritos, CA
","lat":"33.846611","lng":"-118.081933"},{"id":"7565 Carson Blvd, Long
Beach, CA ","lat":"33.825825","lng":"-118.085297"}];

When I try to access the variable "json", IE6 and IE7 tell me that
json is undefined. However "json" is defined when using FF2.

Mysteriously, if I put "alert('hi');" just before my </script> tag,
"json" *does* get defined in IE6&7. Not sure why that would be.

Well the browser has to load and execute the external JavaScript file,
that happens asynchronously.
You will need to set up an onreadystatechange event handler in IE if you
want to run script once the JavaScript file has been loaded.
With Mozilla/Firefox you can set up a load event listener.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top