将文件链接到Javascript程序的最简单方法是什么?

What's the easiest way to link a file to a Javascript program?

本文关键字:最简单 方法 是什么 程序 文件 链接 Javascript      更新时间:2023-09-26

我目前正在制作一个离线的html工具,我需要使用一个很长的对象列表,我已经存储在一个数组中,但这将是太大的方式来存储在我的原始javascript文件

我的问题是:我如何将其存储在文件中,如"DB.txt",我可以在我的javascript程序中重用?

编辑:似乎我是愚蠢的,我这样做的"最简单"的方法就是创建另一个javascript文件,我只是创建一个数组与我所有的值。谢谢大家!

如果您想避免使用像indexedDB这样的小型数据库(如A.Wolff所建议的),您可以创建一个文本文件,然后通过ajax访问它:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'path/to/your/text/file', false);
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == '200') {
        // the responseText property is the content of the file
        // then you can do whatever you want with the file
        console.log('file', xhr.responseText);
    }
};
xhr.send(null);

你也可以把这段代码放在一个带有回调函数的函数中:

function loadAjax(file, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file, false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == '200') {
          callback(xhr.responseText);
        }
    };
    xhr.send(null);
}

然后命名为:

loadAjax('path/to/your/text/file', function(response) {
    console.log('file', response); // content of file
});

或者使用更现代的解决方案(fetch,但是使用旧浏览器的polyfill)或外部库(jQuery, superuser,…)。

此外,您可以将数据存储在json文件中,并且在仍然通过ajax获取数据的同时,轻松解析它。例如:

loadAjax('path/to/your/json/file', function(response) {
    console.log('file', JSON.parse(response)); // content of file
});