7

What would be the equivalent of this approach without jQuery ?

$(function() {
    $.getJSON("datas.json", function(e) {
        var t = [];
        $.each(e, function(e, t) {
            $("div#" + e).text(t)
        })
    })
})

Thanks.

2 Answers2

11

Using plain Javascript your code would look something like this:

function createElements(elements) {
    // Assuming you get an array of objects.
    elements = JSON.parse(elements);

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

var request = new XMLHttpRequest();

request.onload = createElements;
request.open("get", "datas.json", true);
request.send();

Or You can use other cool libraries like superagent and then your code would look like this:

var request = require('superagent');

function createElements(elements) {
    // Assuming you get an array of objects.
    elements = JSON.parse(elements);

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

request.get('datas.json').end(function(error, elements){
    if (!error) {
        createElements(elements);
    }
});
Community
  • 1
  • 1
Gus Ortiz
  • 652
  • 3
  • 9
4

There are a few parts to the code you posted.

$(function(){
  ....
});

This is jQuery's equivalent of window.onload = function(){..}

$.getJSON("datas.json", function(e) {
   ..
});

This is jQuery's ajax get request, for this look at XMLHttpRequest

$.each(e, function(e, t) {
   ..
});

This just does a foreach on the elements in e. Depending on what is returned from your ajax call, you might need a for loop or for...in loop.

$("div#" + e).text(t)

This sets the text of an element, probably replaceable with .innerHTML.

Jamiec
  • 133,658
  • 13
  • 134
  • 193