简体   繁体   中英

Javascript .getJSON .each only works some of the time

I am running into an interesting issue that I cannot figure out. I am dynamically loading some data into an html <select></select> .

What I am discovering is that as I refresh the page, sometimes the data loads, but more often than not, there is nothing there. Is the page loading too quickly or the file not getting processed every time the page reloads?

I have tried multiple browsers and the experience is the same.

Here is my html:

<select id="group-select-user-access" class="blue-text">
     <option value="" disabled selected>Select a Google Group</option>
</select>

Here is my javascript:

<script type="text/javascript">
        var group_list = "json/google_group_list.json";

        $.getJSON(group_list, function(json) {
            $.each(json, function(key) {
                var email_stripped = json[key].substring(0, json[key].lastIndexOf("@"));
                $('select[id=group-select-user-access]').append('<option value="' + email_stripped + '">' + json[key] + '</option>');
            });
        });
</script>

The .json file is simple and in this format:

["email1@test.com", "email2@test.com", "email3@test.com", ...]

I am relatively new when it comes to JS / jQuery so any help is appreciated.

What direction should I head next for troubleshooting?

Probably an issue with the DOM not being fully loaded when you try to modify it

Try either moving your script tag to the very end of your document, or wrap your js code with $(document).ready

$(document).ready(function() {
var group_list = "json/google_group_list.json";

        $.getJSON(group_list, function(json) {
            $.each(json, function(key) {
                var email_stripped = json[key].substring(0, json[key].lastIndexOf("@"));
                $('select[id=group-select-user-access]').append('<option value="' + email_stripped + '">' + json[key] + '</option>');
            });
        });
    })

That way your code will wait until the entire document is loaded before trying to append things to it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM