John Wooten
John Wooten

Reputation: 745

JQuery: parsing ajax call versus imbedded str

I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.

function loadMenuData() {
    $.ajax({
    url: "./shoulders.json",
    success: function(data) {
        dataObj = $.parseJSON(data);
    $.each(dataObj, function( key, value) {
        $(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
    });
    }
});
}
function loadMenuDataX() {
    var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
    dataObj = $.parseJSON(str);
    $.each(dataObj, function( key, value) {
        $(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
    });
}

I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.

  1. I have tried JSON.parse instead of the above and get the same behavior.

  2. I was unable to use $("#dropDownDest") and had to use $(document).find. Why?

  3. Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?

Upvotes: 1

Views: 45

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

What would be a better way to do the ajax version THAT WOULD WORK and be better?

Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :

$.getJSON( "./shoulders.json", function( json ) {
    $.each(json, function( key, value) {
        $("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
    });
});

Hope this helps.

Upvotes: 2

Related Questions