获取数组的静态JSON文件

时间:2018-05-18 13:43:31

标签: javascript httprequest fetch

我是学生,也是JS的新手。

我需要帮助才能解决问题。我有很多信息,所以我想使用一个静态的JSON文件(json.data)。我如何使用fetch?我查看了一些示例,但不了解如何使用我的代码。我会非常感谢你的帮助,我已经坚持了一个星期。



// 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"
    }
]
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

Fetch example

fetch('https://api.myjson.com/bins/176t5e')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
        handleData(myJson);

  });

旧答案 您可以使用XMLHttpRequest

创建新的XMLHttpRequest个实例,并在handleData内调用onreadystatechange个功能。

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        handleData(JSON.parse(xhttp.responseText));
    }
};
xhttp.open("GET", "yourJson.json", true);
xhttp.send();

我上传了你的json数据here。并sample example