javascript 等效于没有 jQuery 的 getJSON 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28879696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent of getJSON function without jQuery
提问by Gus Ortiz
What would be the equivalent of this approach without jQuery ?
如果没有 jQuery,这种方法的等价物是什么?
$(function() {
$.getJSON("datas.json", function(e) {
var t = [];
$.each(e, function(e, t) {
$("div#" + e).text(t)
})
})
})
Thanks.
谢谢。
回答by Gus Ortiz
Using plain javascript your code would look something like this:
使用普通的 javascript,您的代码将如下所示:
function createElements(elements) {
// Assuming you get an array of objects.
elements = JSON.parse(elements);
elements.forEach(funciton (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 superagentand then your code would look like this:
或者您可以使用其他很酷的库,例如superagent,然后您的代码将如下所示:
var request = require('superagent');
function createElements(elements) {
// Assuming you get an array of objects.
elements = JSON.parse(elements);
elements.forEach(funciton (element) {
var div = document.getElementById(element.id);
div.innerHTML = element.text;
});
}
request.get('datas.json').end(function(error, elements){
if (!error) {
createElements(elements);
}
});
回答by Jamiec
There are a few parts to the code you posted.
您发布的代码有几个部分。
$(function(){
....
});
This is jQuery's equivalent of window.onload = function(){..}
这相当于 jQuery window.onload = function(){..}
$.getJSON("datas.json", function(e) {
..
});
This is jQuery's ajax get request, for this look at XMLHttpRequest
这是 jQuery 的 ajax get 请求,为此请查看 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.
这只是对e
. 根据您的 ajax 调用返回的内容,您可能需要一个for
循环或for...in
循环。
$("div#" + e).text(t)
This sets the text of an element, probably replaceable with .innerHTML
.
这会设置元素的文本,可能可以替换为.innerHTML
.