Search code examples
javascripthtmljsonxmlhttprequest

retrieving a url from a json file in JavaScript


I have a JSON file that contains a URL which my current XMLHttpRequest retrieves, but when I click on the link I get "Cannot GET /url". The JSON contains company information like this:

  {
    "company": "Nike",
    "webAddress": "https://www.nike.com/",
    "accessories": "Yes",
    "component": "No",
    "clothing": "Yes",
    "holiday": "No",
    "insurance": "No",
    "nutrition": "No",
    "association": "No",
    "location": "USA"
    }

I retrieve the JSON file like this:

function loadAllBrands(e) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'brands.json', true);

  xhr.onload = function() {
    if(this.status === 200) {
      // console.log(this.responseText);

      const customers = JSON.parse(this.responseText);

      let output = '';
      
      customers.forEach(function(item) {
        output += `
          <div class="w3-card-4 w3-white w3-large card-margin">
            <ul>
              <h2 class="card-title">${item.company}</h2>
              <li><a href="url" class="w3-text-blue">${item.webAddress}</a></li>
              <li>Location: ${item.location}</li>            
              <li>Accessories: ${item.accessories}</li>
              <li>Components: ${item.component}</li>
              <li>Clothing: ${item.clothing}</li>
              <li>Holidays: ${item.holiday}</li>
              <li>Insurance: ${item.insurance}</li>
              <li>Nutrition: ${item.nutrition}</li>
              <li>Association: ${item.association}</li>
            </ul>
          </div>
          `;
      })
        document.getElementById('output').innerHTML = output;
    }
  }  
  xhr.send();
};

How do I make a clickable link that takes the user to the web Address?


Solution

  • Like Heretic Monkey said, replace "url" with "${item.webAddress}" in this line:

    <li><a href="url" class="w3-text-blue">${item.webAddress}</a></li>