Skip to content Skip to sidebar Skip to footer

Fill Element With Value In A Json

I have this type of json: { 'datas': [ { 'id': 'fruit_name', 'value': 'Banana' }, { 'id': 'fruit_description',

Solution 1:

request is probably not defined (in scope) in your function. Either you can call it and use this or of the following

function createElements(request) {//Get the 'request' passed.
    // Parse JSON response.
    var elements = JSON.parse(request.responseText);

    elements.datas.forEach(function (element) {
        var div = document.getElementById(element.id);
        div.innerHTML = element.value;
    });
}

var request = new XMLHttpRequest();    
request.onreadystatechange = function() {
    if (request.readyState === 4) {
        createElements(request);//Pass in 'request'
    }
}

request.responseType = "application/json";//Remove line if there are errors
request.open("GET", "datas.json", true);
request.send();

Post a Comment for "Fill Element With Value In A Json"