Equivalent of getJSON function without jQuery [duplicate]
Asked Answered
S

2

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.

Sherrer answered 5/3, 2015 at 14:5 Comment(8)
do you mean without jquery? because it is pure JS already.Munguia
what effort have you made?Munguia
Check this site: youmightnotneedjquery.com/#json for JSON AJAX request. Use simple for loop or forEach instead of $.each.Ayo
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?Tangy
#8567614Vitelline
I'm sorry but $.getJSONis a jQuery function...Sherrer
@poipoi jQuery is pure JS. It's just a library of js functions.Kirshbaum
We play a little bit with the words here.Sherrer
D
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);
    }
});
Deniable answered 5/3, 2015 at 14:37 Comment(0)
A
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.

A answered 5/3, 2015 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.