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.
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.
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);
}
});
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
.
© 2022 - 2024 — McMap. All rights reserved.
forEach
instead of$.each
. – Ayo$.getJSON
is a jQuery function... – Sherrer