Question

I'm currently writing a web application that requires some data from the server to be stored in a Javascript object. The amount of data that needs to be loaded is very small, probably around 1 KB. I'm faced with the decision of how to load the data into the application. Here are the two obvious (to me anyway) paths I could take:

1 - Using jQuery's document-ready function, I make an AJAX request to the server and store the response in the appropriate Javascript object. It might look something like this.

$(function() {
    $.get('index.php?get=data', function(data) {
        myObj.addData(data);
    });
});

2 - The alternative would be to send the data along with the page during the initial page request. In order to do that, I would have my server generate the data and output it in the markup between <script> tags. Since my current project is in PHP, it would look something like this:

...
</div>
<script>
    window.myData = <?= json_encode($myData) ?>;
</script>
...

The jQuery document-ready function would later look for the global variable called window.myData and load it into the appropriate Javascript object like this:

$(function() {
    myObj.addData(window.myData);
});

Is there a preferred way of loading data into Javascript objects? Although the amount of data being stored is relatively small, the AJAX call could result in a longer wait if the server's ping isn't great. However, it would seem that AJAX calls are more popular when it comes to these things. Is there a valid reason?


EDIT: The data would very rarely be changed (maybe once a year). Therefore, browser caching should not be much of an issue.

Was it helpful?

Solution

use the $.getJSON method:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

OR could use the $.each() function to loop through the data:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top