Bhawna Tuteja

Bhawna Tuteja

  • NA
  • 544
  • 264.1k

Error while fetching data from Json File in Javascript

Aug 11 2020 2:18 AM
I have a json file and I wanted to display data from that file to HTML. I have written code but while coding it is giving error as 'Type Error: Failed To Fetch'
 
Here is the code of various files
 
JSON File
  1. [    
  2.     {    
  3.         "id""1",    
  4.         "firstName""John",    
  5.         "lastName""Doe"    
  6.     },    
  7.     {    
  8.         "id""2",    
  9.         "firstName""Mary",    
  10.         "lastName""Peterson"    
  11.     },    
  12.     {    
  13.         "id""3",    
  14.         "firstName""George",    
  15.         "lastName""Hansen"    
  16.     }    
  17. ]  
  1. fetch('DisplayData.json')    
  2.     .then(function (response) {    
  3.         alert('Inside Fetch');    
  4.         return response.json();    
  5.     })    
  6.     .then(function (data) {    
  7.         appendData(data);    
  8.     })    
  9.     .catch(function (err) {    
  10.         alert('Error Occured' + err);    
  11.     });    
  12.     
  13. function appendData(data) {    
  14.     alert('Inside function');    
  15.     var m = document.getElementById("mDiv");    
  16.     for (var i = 0; i < data.length; i++) {    
  17.         var div = document.createElement("div");    
  18.         div.innerHTML = 'Name: ' + data[i].firstName + ' ' + data[i].lastName;    
  19.         m.appendChild(div);    
  20.     }    
  21. }  
  1. <html>  
  2. <script src="DisplayData.js"></script>  
  3. <body>  
  4. <div id= "mDiv">  
  5. </div>  
  6. </body>`enter code here`  
  7. </html>  

Answers (4)