如何在没有jQuery的JavaScript中打开JSON文件?

前端之家收集整理的这篇文章主要介绍了如何在没有jQuery的JavaScript中打开JSON文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在JavaScript中编写一些代码。在这段代码中,我想读一个json文件。该文件将从URL加载。

如何在JavaScript中的对象中获取JSON文件内容

这是例如我的JSON文件位于../json/main.json:

  1. {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',{vehicle:'3',description:'nothing to say'}]}

我想在我的table.js文件中使用它:

  1. for (var i in mainStore)
  2. {
  3. document.write('<tr class="columnHeaders">');
  4. document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
  5. document.write('<td >'+ mainStore[i]['description'] + '</td>');
  6. document.write('</tr>');
  7. }

解决方法

这里有一个不需要jQuery的例子:
  1. function loadJSON(path,success,error)
  2. {
  3. var xhr = new XMLHttpRequest();
  4. xhr.onreadystatechange = function()
  5. {
  6. if (xhr.readyState === XMLHttpRequest.DONE) {
  7. if (xhr.status === 200) {
  8. if (success)
  9. success(JSON.parse(xhr.responseText));
  10. } else {
  11. if (error)
  12. error(xhr);
  13. }
  14. }
  15. };
  16. xhr.open("GET",path,true);
  17. xhr.send();
  18. }

称为:

  1. loadJSON('my-file.json',function(data) { console.log(data); },function(xhr) { console.error(xhr); }
  2. );

猜你在找的jQuery相关文章