3

I'm student and new to JS.

I need help to solve a problem. I have a lot of information so I want to use a static JSON file (json.data) insted of a array. How do I use fetch? I checked some examples but don't understand how to get it work with my code. I would be very thankful for some help, I have been stuck on this for a week.

// 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"
    }
]

7
  • What do you mean my fetch data? Do you want the JS to read file from your hard drive instead hard coding? JS do not have direct access to local drive unless given permission explicitly. This link may be helpful: stackoverflow.com/questions/7346563/loading-local-json-file Commented May 18, 2018 at 13:46
  • You may want to look up "Ajax" if you need to fetch external data using javascript Commented May 18, 2018 at 13:48
  • Can you tell us what the problem you're having is? Have you tried something and had it fail? If so, tell us what you tried and what happened. If you don't even know where to start, what are the things you're confused by? What kinds of specific questions do you have about those examples you've looked at? Commented May 18, 2018 at 13:49
  • @Erika what didn't work about the fetch() line above? As long as that data.json file's contents are identical to what you've posted in the data variable above (and that file is available to wherever you're running this JS), that fetch line should work. Commented May 18, 2018 at 14:36
  • See my edit above, that's how I tried to do. Maybe it's something missing in the JSON file or the code. Commented May 18, 2018 at 17:52

1 Answer 1

3

Fetch example.

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

  });

Old Answer You can use XMLHttpRequest.

Create a new XMLHttpRequest instance and call your handleData function inside 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();

I uploaded your json data here. And sample example.

Sign up to request clarification or add additional context in comments.

2 Comments

The OP is requesting information for the Fetch API ("How do I use fetch?") which is gradually replacing XMLHttpRequest() developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch as the recommended approach.
@BigBlueHat you're right. i'm sorry and updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.