如何从另一个文件读取数组数据

How to read an array data from another file?

本文关键字:读取 数组 数据 文件 另一个      更新时间:2023-09-26

我将本网站的内容转移到App/data/names.js目录下的文件中:https://raw.githubusercontent.com/dominictarr/random-name/master/names.json

我这样做是因为数组太大,不能放在我写代码的文件中,并显式地用它初始化变量。但是,我还是想把它赋值给我创建的变量。我有这样的想法。

var arrayOfNames = readJSonFromFile("path");

有可能实现吗?

就像这样!

$.getJSON('path', function (arrayOfNames) {
// do things with your arrayOfNames
} );

你可以从JavaScript中通过HTTP请求获取文档,就像这样:

function do_something(arrayOfNames) {
  console.log(arrayOfNames)
}
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://raw.githubusercontent.com/dominictarr/random-name/master/names.json', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      do_something(JSON.parse(xhr.responseText))
    }
  }
}
xhr.send()

请注意,这可能不适用于旧的浏览器。根据您是否使用JavaScript框架,可能有一个更短的解决方案。