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.

8
  • 2
    do you mean without jquery? because it is pure JS already. Commented Mar 5, 2015 at 14:06
  • what effort have you made? Commented Mar 5, 2015 at 14:07
  • 2
    Check this site: youmightnotneedjquery.com/#json for JSON AJAX request. Use simple for loop or forEach instead of $.each. Commented Mar 5, 2015 at 14:07
  • This is too broad and that code does quite a lot of different things. What specific problem are you having? Making an HTTP request? Parsing JSON? Looping over an object? Commented Mar 5, 2015 at 14:07
  • 2
    @poipoi jQuery is pure JS. It's just a library of js functions. Commented Mar 5, 2015 at 14:09

2 Answers 2

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments