我的网站将字符串存储在json文件中,并使用javascript将值重新转换为HTML。这是函数的简化版本。
HTML:
<html>
<head>
<script src="script.js"></script>
</head>
<body>
This is a demonstration. The author is:
<div>
<div class="author"></div>
</div>
</body>
</html>
使用Javascript:
request = new XMLHttpRequest();
request.open('GET', 'data.json', true);
request.onload = function () {
obj = JSON.parse(request.responseText);
obj.forEach(function (d) {
var el = document.createElement('p');
el.textContent = d.author;
document.getElementsByClassName('author')[0].appendChild(el);
});
};
request.send();
JSON:
{
"author": "John Doe"
}
实施:http://embed.plnkr.co/Ixrz9R2KVLXpOqa7mwyU
代码不会在HTML中返回作者姓名。如果可能的话,如果不使用jQuery就可以做到这一点。
答案 0 :(得分:1)
你必须加载这样的脚本:
<script src="script.js"></script>
删除
<link href="script.js">
,然后把
<script src="script.js"></script>
在</body>
之前。
我建议您将脚本放在</body>
之前,以便在加载DOM元素后执行它。
[
{"author": "K."},
{"author": "Hello world"},
{"author": "John Doe"}
]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="author" content="K.">
<title>Demo</title>
</head>
<body>
<p>This is a demonstration. The author is:</p>
<div class="author"></div>
<script src="script.js"></script>
</body>
</html>
const request = new XMLHttpRequest; // `()` isn't needed.
request.open("GET", "data.json", true);
request.addEventListener("load", _ => { // Arrow function
const parsed = JSON.parse(request.responseText);
parsed.forEach(({author}) => { // Destructuring, Arrow function, ...
const authorElement = document.createElement("P");
authorElement.textContent = author;
document.querySelector(".author").appendChild(authorElement);
});
});
request.send();