T
T
tarthur2017-06-06 11:05:21
JavaScript
tarthur, 2017-06-06 11:05:21

How to get JSON data?

Hello.
There is such a country.io/names.json
How to get this data in pure JS, what would be further use of it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikita Gushchin, 2017-06-06
@iNikNik

On pure JS - browsers have had fetch api for a long time:

fetch('http://country.io/names.json')
  .then(r => r.json())
  .then(names => console.log('Names arrived!', names)

You can find out more from the documentation:
  • https://developer.mozilla.org/en/docs/Web/API/Fetch_API
    Well, do not forget about CORS - if the server does not return these headers, then the request to another domain will not work.

D
Dmitry Eremin, 2017-06-06
@EreminD

On pure JS, like this
, the address itself, where to knock, you have

var names = {} //тут у нас будет результат
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://country.io/names.json', false);
xhr.send();
if (xhr.status != 200) {
  // обработать ошибку
  alert( xhr.status + ': ' + xhr.statusText ); // пример вывода: 404: Not Found
} else {
  // вывести результат
  names = xhr.responseText;
}

A
Andrey Pavlenko, 2017-06-06
@Akdmeh

https://www.w3schools.com/js/js_json_parse.asp
for >=IE 8

H
holymotion, 2017-06-06
@holymotion

You most likely have a CORS error and the server is not returning the Access-Control-Allow-Origin: * header. If you don't need to send any headers to the server try using jsonp. https://www.npmjs.com/package/fetch-jsonp - maybe suitable for react
https://learn.javascript.ru/ajax-jsonp - js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question