最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - load json from external file - Stack Overflow

programmeradmin0浏览0评论

I've never touched on JSON, but I just need some bits clearing up so that I can research how to solve my problem properly.

I have -HTML file -JS file -JSON file. All are linked in the html file.

My challenge is to load the JSON file and add together some of the values that are located within it. So far I'm struggling to find anything other than JQuery to open it... I can find things about parsing, but many examples use code inline and i'm lost as to whether they're coding on the js file or the JSON one!

I'm seeing AJAX mentioned too, but i plead ignorance to its use so far (i'm very new to JS). so, what would you remend to load it? what should i research to see about obtaining the values and creating additions with them?

I've never touched on JSON, but I just need some bits clearing up so that I can research how to solve my problem properly.

I have -HTML file -JS file -JSON file. All are linked in the html file.

My challenge is to load the JSON file and add together some of the values that are located within it. So far I'm struggling to find anything other than JQuery to open it... I can find things about parsing, but many examples use code inline and i'm lost as to whether they're coding on the js file or the JSON one!

I'm seeing AJAX mentioned too, but i plead ignorance to its use so far (i'm very new to JS). so, what would you remend to load it? what should i research to see about obtaining the values and creating additions with them?

Share Improve this question asked Nov 27, 2014 at 18:06 Leah ThompsonLeah Thompson 451 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Loading a JSON file:

jQuery:

$.getJSON('/my/url', function(data) {
  console.log(data);
});

Non-jQuery:

request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    var data = JSON.parse(request.responseText);
    console.log(data);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

note the console.log prints the contents of the JSON file to the javascript console. You can do whatever you want with the "data" variable.

发布评论

评论列表(0)

  1. 暂无评论