Dino Geek, try to help you

How to load a JSON file from a server in JavaScript?


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();
```


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use