js snippets

加载json(注意跨域)

a.

1
2
3
4
5
6
7
8
fetch(jsonurl)
  .then(function(response) {
    return response.json();
  })
  .then(function(myjson) {
    console.log(json.stringify(myjson));
  });

b.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
    xhr.send();
};

getJSON(jsonUrl, function(err, data) {
  if (err !== null) {
    console.log('Something went wrong: ' + err);
  } else {
      console.log(data['001']);
  }
});

参考: How to get JSON from URL in JavaScript?

go snippets
小米k20p刷机
comments powered by Disqus