2

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?

Cesar
  • 2,229
  • 1
  • 22
  • 20
  • [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – mavili Jul 26 '13 at 14:56
  • 1
    I don't think you need `type="application/json"`, you can use `type="text/javascript"`. I think your script will be there on the page, but it's not assigned to anything, so you have a couple of options. 1. Set it equal to something: `var json = ...`. 2. pass it to a function. – Tim Mac Jul 26 '13 at 15:01
  • If I there's flexibility to modify `mystates.json`, I'd modify it to look into look like: `preExistingJSFunction([{"States":{..}..}])`. Google for JSONP. It's much similar to your usage of script tag. :) – UltraInstinct Jul 26 '13 at 15:04
  • Thanks Tim. But how would I be able to tell my javascript json variable to use the embeded json/js file? I've seen examples where people hardcode the json into the javascript but I want to use the separate file. – Cesar Jul 26 '13 at 15:04
  • 1
    .. Or the other option is to have your server side side script inject the contents of the JSON file into a JS variable in script tag area of your HTML. That way, you can still have it as a separate file. – UltraInstinct Jul 26 '13 at 15:07

1 Answers1

2

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.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
  • Thank you! This worked. Took me a bit because I had my function declared after the json file was attached. – Cesar Jul 26 '13 at 15:24