Reputation: 2369
I have a list of specific states I want to load into a dropdown list on page load. Because of this I don't have the need for AJAX and thus want to avoid it. How can I access the json file within my page load?
This is what I have.
My JSON file contains:
[{"States":{"AL" : "Alabama", "AK" : "Alaska", "WI" : "Wisconsin", "WY" : "Wyoming" }}]
How I load it onto my HTML header.
<script type="application/json" src="mystates.json"></script>
How can I access the above with Javascript?
Upvotes: 2
Views: 4420
Reputation: 44444
I'll put my comments as answer here.
Using AJAX is the easiest way in case like these, esp. using $.getJSON(..)
as @mavili suggested.
If you are unwilling to have an async request, you have two options(in my opinion, YMMV :) )
Have a Javascript function, which takes in one parameter like:
function saveStates(statesObject) {
/* store states here */
}
and then have your states JSON file modified to look like this:
saveStates([{"States":{"AL" : "Alabama", "AK" : "Alaska", ..}..}])
Now, simply include this file as you'd usually do in your HTML.
Or the other option is have your server side script read the the file contents and inject the contents into the HTML (javascript <script>
area).
In both of the approaches your JSON file can be separately changed.
Upvotes: 2