javascriptjsonparsinggetjsonsynchronous

How to include JSON data in javascript synchronously without parsing?



I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.

I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.

Is there a way to load JSON in a synch way without doing your own parsing?
(more or less like using a <script language="JavaScript" src="MyArray.json"></script>)

Thanks in advance for any help, hope it makes sense since I am a javascript newbie. Paolo


Solution

  • getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.

    $.ajax({
      url: 'MyArray.json',
      async: false,
      dataType: 'json',
      success: function (response) {
        // do stuff with response.
      }
    });
    

    You still use a callback with async:false but it fires before it execution continues on from the ajax call.