Local JSON file AJAX request Setup and code
You cannot use the file protocol to make an AJAX request locally. The below steps will walk through how to use Visual Studio Code and the Live Server extension to run a local host on your computer. This will allow you to use JavaScript fetch to make a request to a JSON file that is local within your machine.
Make an AJAX request to local JSON file
You must use the http protocol to do an AJAX request to the json file.
Suggested editor is https://code.visualstudio.com/
Set up Local server within Visual Studio Code Use of live server is https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
Do not use the file: protocol to make AJAX requests with JavaScript!
file:// is a request for a local file.?
https:// is using HTTP protocol to request a file from the web or from your local computer.
Files requested via file:// get opened from local drive. A file requested via https:// get opened via HTTP request to the URL that comes after it.
https:// is running the same file that did not work in the file protocol. ? The local host will include the local IP address https://127.0.0.1:5500/index.html? or the https://localhost:5500/index.html? are both valid paths to the local server running.
In visual studio code right click in the open space or run the live server from the shortcut once it's installed.
Open the live server on the html file, your workspace will need an index file which will be the default location where the local host opens.
If you see the file: in the URL bar you need to set up a local host to make AJAX requests.
Exercise :
HTML
<!DOCTYPE html>
<html><head><title>JavaScript Course</title></head>
<body>
???<div class="container"></div>
???<button id="btn">Start</button>
???<script src="js1.js"></script>
</body></html>
JavaScript
const btn = document.querySelector('#btn');
const output = document.querySelector('.container');
const url = 'temp1.json';
//console.log(btn);
btn.onclick = ()=>{
???//console.log('clicked');
???fetch(url)
领英推荐
???.then(res => res.json())
???.then(data => {
???????addData(data);
???})
}
?
function addData(data){
???let html = '<h1>Results</h1>';
???data.forEach(person=>{
???????console.log(person);
???????html += `<div>${person.first} ${person.last} (${person.id})</div>`;
???})
???output.innerHTML = html;
}
?JSON
[
???{
???????"first" : "Laurence",
???????"last" : "Svekis",
???????"id" : 100
???},
???{
???????"first" : "Adam",
???????"last" : "Jones",
???????"id" : 44
???},
???{
???????"first" : "Jane",
???????"last" : "Doe",
???????"id" : 25
???}
]
Web Developer Local Setup