所以我有一个javascript文件,该文件从json文件中提取内容,并使用该数据填充名为“ content”的索引页上的div,这是我的javascript文件,但当前我的索引页为空白:
var wrapper = document.getElementById("content");
function init() {
loadJSON(function(e) {
for (var t = JSON.parse(e), n = Object.keys(t.film).length, a = 0; a < n; a++) {
var i = document.createElement("img");
i.src = t.films[a].url, i.setAttribute("class", "filmimage"), wrapper.appendChild(i)
}
})
}
function loadJSON(e) {
var t = new XMLHttpRequest;
t.overrideMimeType("application/json"),
t.open("GET", "dist/json/data.json", !0),
t.onreadystatechange = function() {
4 === t.readyState && "200" === t.status && e(t.responseText)
}, t.send(null)
}
document.addEventListener("DOMContentLoaded", function() {
init()
});
答案 0 :(得分:0)
以下是使用fetch()
而不是过时的XMLHttpRequest
固定的脚本:
var wrapper = document.getElementById("content");
function init() {
fetch("dist/json/data.json").then(r => r.json())
.then(data => {
data.films.forEach(film => {
var i = document.createElement("img");
i.src = film.url;
i.classList.add("filmimage"); // use CSS instead: #content img { ... }
wrapper.appendChild(i)
});
})
.catch(e => console.log(e));
}
document.addEventListener("DOMContentLoaded", init);
答案 1 :(得分:0)
您可以在js文件中使用此代码
var wrapper = document.getElementById("content");
function init() {
loadJSON(function(e) {
console.log(e);
for (var t = JSON.parse(e), n = Object.keys(t.films).length, a = 0; a < n; a++) {
var i = document.createElement("img");
i.src = t.films[a].url, i.setAttribute("class", "filmimage"), wrapper.appendChild(i)
}
});
}
function loadJSON(e) {
var t = new XMLHttpRequest;
t.overrideMimeType("application/json"),
t.open("GET", "dist/json/data.json", !0),
t.onreadystatechange = function() {
4 === t.readyState && "200" == t.status && e(t.responseText)
}, t.send(null)
}
init();