【发布时间】:2018-05-18 13:43:31
【问题描述】:
我是学生,是 JS 的新手。
我需要帮助来解决问题。我有很多信息,所以我想使用一个包含数组的静态 JSON 文件 (json.data)。如何使用获取?我检查了一些示例,但不明白如何让它与我的代码一起使用。我将非常感谢您的帮助,我已经坚持了一周。
// Loop through all my properties to display info on page 2
let page2 = (hairdresser) => {
let singleView = "<div>";
for(prop in hairdresser){
if(hairdresser.hasOwnProperty(prop)){
singleView += `${hairdresser[prop]} </p>`;
}
}
singleView += "</div>"
document.body.innerHTML = singleView;
}
// handleData function for page 1
let handleData = (hairdressers) => {
let out = "<table>";
hairdressers.forEach((hairdresser, index) => {
out += "<tr>";
const printableProps = ["time", "name", "price", "timeEst", "rating", "adress"];
printableProps.forEach(prop => {
if (hairdresser.hasOwnProperty(prop)) {
let isName = prop === "name";
out += `<td>
${isName ? `<a href="#" onclick='page2(${JSON.stringify(hairdresser)})'}>` : ""}
${hairdresser[prop]}
${isName ? '</a>' : ""}
</td>`;
}
});
out += "</tr>";
})
out += "</table>";
document.body.innerHTML = out;
}
fetch("/path/to/data.json").then(res => res.json()).then(handleData);
**My JSON file:**
[
{
"name" : "Sax & Fön",
"adress" : "Rådmansgatan 46",
"zip" : "113 57 Stockholm",
"time" : "12",
"tel" : "08-522 389 20",
"site" : "www.salongweb.se",
"rating" : "(32)",
"price" : "320 kr",
"timeEst" : "30 min",
"open" : "Öppet till 19.00 idag",
"desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
},
{
"name" : "Hårley Davidson",
"adress" : "Rådmansgatan 45",
"zip" : "113 57 Stockholm",
"time" : "12",
"tel" : "08-522 389 20",
"site" : "www.salongweb.se",
"rating" : "(32)",
"price" : "320 kr",
"timeEst" : "30 min",
"open" : "Öppet till 19.00 idag",
"desc" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris"
}
]
【问题讨论】:
-
我的
fetch数据是什么意思?你想让 JS 从你的硬盘读取文件而不是硬编码吗?除非明确给予许可,否则 JS 无法直接访问本地驱动器。此链接可能会有所帮助:stackoverflow.com/questions/7346563/loading-local-json-file -
如果您需要使用 javascript 获取外部数据,您可能需要查找“Ajax”
-
您能告诉我们您遇到的问题是什么吗?您是否尝试过某些事情并失败了?如果是这样,请告诉我们您尝试了什么以及发生了什么。如果您甚至不知道从哪里开始,那么您对哪些事情感到困惑?对于您看过的这些示例,您有哪些具体问题?
-
@Erika 上面的 fetch() 行有什么问题?只要该
data.json文件的内容与您在上面的data变量中发布的内容相同(并且该文件可用于您运行此 JS 的任何位置),那么该 fetch 行应该可以工作。 -
查看我上面的编辑,这就是我尝试做的。可能是 JSON 文件或代码中缺少某些内容。
标签: javascript httprequest fetch