You can use the Fetch API in JavaScript to load a JSON file from a server. Here’s a simple example:
```
fetch(“https://example.com/file.json”)
.then(response => {
if (!response.ok) {
throw new Error(“HTTP error “ + response.status);
}
return response.json();
})
.then(json => {
console.log(json);
})
.catch(function() {
console.log(“There is an error in the network request.”);
});
```
In the above code:
1. We’re using `fetch()` to send a GET request to “https://example.com/file.json”.
2. This returns a Promise that resolves to the Response to that request, whether it is successful or not.
3. We check if the response is successful via `response.ok`.
4. We then parse the response body as JSON using `response.json()`. This also returns a Promise.
5. In the next `then()` block, we have the resulting JSON.
6. If there were network problems or if the response isn’t ok, we catch the errors in the `catch()` block.
The Fetch API is a modern replacement for `XMLHttpRequest`. Please note the Fetch API is not supported in Internet Explorer.
For older browsers, you might need to use XMLHttpRequest like below:
```
var request = new XMLHttpRequest();
request.open(‘GET’, ‘https://example.com/file.json’, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
console.log(data);
} else {
console.log(‘Server returned an error’);
}
};
request.onerror = function() {
console.log(‘There was a connection error of some sort’);
};
request.send();
```