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

时间:2016-09-17 12:44:43

标签: javascript database file external

我目前正在制作一个离线html工具,我需要使用一个loooong的objets列表,我已经存储在一个数组中但是这个太大了,不能存储在我原来的javascript文件中。

我的问题是:如何将其存储在一个文件中,例如“DB.txt”,然后我可以在我的javascript程序中重复使用?

编辑:我觉得我很愚蠢,对我来说“最简单”的方法就是创建另一个javascript文件,我只需创建一个包含所有值的数组。谢谢大家!

1 个答案:

答案 0 :(得分:1)

如果您想避免使用像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,超级用户......)。

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

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