简体   繁体   English

Javascript 读取 JSON 文件,然后以 HTML 格式显示

[英]Javascript reading a JSON file and then display it in HTML

Hello guys first i want to declare that i am completly newbie with json and with javascript too.大家好,首先我想声明我完全是 json 和 javascript 的新手。 I am making a blogspot with html and css and i want get the data of the articles from a json file.Now I've made a JSON file which stores some data the json file is this.我正在用 html 和 css 制作一个 blogspot,我想从 json 文件中获取文章的数据。现在我制作了一个 JSON 文件,它存储了一些数据,json 文件就是这个。

content.json内容.json

articles = {
"blackHeli" : "black helicopters covered the sea..",
"jfk": "the assassination of kennedy..."}

Now i want to make a javascript file which taking this data and displaying it in HTML.现在我想制作一个 javascript 文件来获取这些数据并以 HTML 显示它。 I saw some examples but i thought that it was very complex for my programming level.One of them is this block of code我看到了一些例子,但我认为这对我的编程水平来说非常复杂。其中一个是这段代码

function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4 && rawFile.status == "200") {
        callback(rawFile.responseText);
    }
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});

There is any simpler way to make a file reader with javascript and displaying this in my blogspot?有什么更简单的方法可以使用 javascript 制作文件阅读器并在我的 blogspot 中显示它?

Thanks for your time :)谢谢你的时间 :)

This might help you:这可能会帮助您:

(The articles is a javascript object, not located in a json file) (文章是一个 javascript 对象,不在 json 文件中)

const articles = {
  "blackHeli" : "black helicopters covered the sea..",
  "jfk": "the assassination of kennedy..."
}
Object.keys(articles).forEach(function (articleName) {
  const articleDiv = document.createElement('div');
  articleDiv.innerHTML = `
    <h1>${articleName}</h1>
    <p>${articles[articleName]}</p>
  `
  document.body.appendChild(articleDiv)
})

It's basically a loop which creates an element (articleDiv) with two elements inside it, the h1 with it's title, and the p with it's content.它基本上是一个循环,它创建一个元素(articleDiv),其中包含两个元素,h1 带有标题,p 带有内容。

  • articleName : refers to the Article name articleName :指的是文章名称
  • articles[articleName] : refers to the Article content文章[文章名称] : 指文章内容
  • articleDiv : refers to the article element articleDiv :指的是文章元素

Hope this helps you :)希望这对你有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM