2

I'd like to ask for some help. I have an external JSON file with an array inside looking like this:

{ "Files": [
    {
        "fileName": "Trains",
        "fileID": "t1"
    },
    {
        "fileName": "Planes",
        "fileID": "p1"
    },
    {
        "fileName": "Cars",
        "fileID": "c1"
    }
]}

I'm trying to use this data ultimately to fill a dropdown select menu in an XHTML page whilst using JavaScript to write it. So far I've got the following but can't now figure out where I'm going wrong for the final hurdle. Any pointers on what I'm not understanding appreciated, thanks.

function fileDropdown() {
    var options = "";
    $.getJSON(
        "json/files.json", 
        function(result) {
            //find the array and do seomthing
            $.each(result.Files, function(key, val) {
                options += '<option value="' + val.fileID + '">' + val.fileName + '</option>';
            });
        }
    );
    document.write("<select>"+options+"</select>");
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
neilfoxholes
  • 45
  • 1
  • 6

3 Answers3

1

Try this:

function fileDropdown()
{

$.getJSON("json/files.json", function(result) {
//find the array and do seomthing
    var options = "";
    $.each(result.Files, function(key, val) {
        options += '<option value="' + val.fileID + '">' + val.fileName + '</option>';
    });
    var select = $('<select/>');
    select.append(options);
    $(document.body).append(select);
});
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

Thanks, solved the issue now. Would upvote you but require more reputation.

I used

$.each(result.Files, function(file) {
        selectElement.append($('<option value="' + this.fileID + '">' + this.fileName + '</option>'));
neilfoxholes
  • 45
  • 1
  • 6
0

$.getJSON("json/files.json", ...) means "take window.location, append json/files.json and then send a GET request with this URL".

To fix this, you can use an absolute file: URL. But your browser will probably refuse to load the file for security reasons.

The alternative is to make your web server send the file to the browser when it requests the above URL.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820