سؤال

I'm building a proof of concept for my first responsive web-site with JavaScript, JQuery, and Bootstrap. At this time I'm prototyping the front-end only.

I need to dynamically insert the content from a text file with JSON content (in a final application it will come from a server-side database) into my HTML.

I have the following structure of index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Home Page</title>

        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

    </head>
    <body>

       ...
       <ul class="list-unstyled" id="itemList">
           <!-- JQuery function will be called when DOM is ready -->
       </ul>
       ...

       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
       <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js">/script>
       <script src="my.js"></script>
       <script>
            $( document ).ready("fillInData('text.json')");
       </script>
    </body>
</html>

In my.js I have the following code:

function fillInData (dataFile) {
    // remove any existing content
    var ft = $('#itemList');
    ft.empty();

    // populate new stuff from a co-located JSON file
    var htmlString = "";
    $.getJSON(dataFile, function(data) {
        $.each(data.items, function(i, item) {
            htmlString += '<li>' + item.name + ...;
            ...
            htmlString += '</li>'
        });
    });
    ft.innerHTML = htmlString;
}

My problem is that it does not seem that fillInData functioned is called at all.

Since the ready event should not be fired before the entire body is parsed, I do not believe that I placed the hook too far down.

I use Chrome Dev Tools for debugging. I placed a breakpoint inside my JS function, expecting to go step-by-step from there, but the breakpoint was never reached.

Am I missing something obvious here? Could it be just a RTFM case?

هل كانت مفيدة؟

المحلول

It's

$(document).ready(function() {
    fillInData('text.json');
});

passing a string to $.ready() doesn't really work

EDIT:

and fix your ajax

$.getJSON(dataFile, function(data) {
    var htmlString = "";

    $.each(data.items, function(i, item) {
        htmlString += '<li>' + item.name + ...;
        ...
        htmlString += '</li>'
    });

    ft.html(htmlString); // it's a jQuery object, and it's async

});

نصائح أخرى

will this hit your breakpoint?

$(document).ready(function(){ fillInData('text.json'); });

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top