簡體   English   中英

將文件鏈接到 Javascript 程序的最簡單方法是什么?

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

我目前正在制作一個離線 html 工具,我需要使用我存儲在數組中的對象的 loooong 列表,但這對於存儲在我的原始 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、超級用戶等)。

此外,您可以將數據存儲在一個 json 文件中,並且在仍然通過 ajax 獲取它的同時,輕松解析它。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM