2016-09-17 66 views
-1

我目前正在製作一個小離線html工具,我需要使用一個loobong列表,我已經存儲在一個數組中,但這將太大而無法存儲在我原來的JavaScript文件中。將文件鏈接到Javascript程序的最簡單方法是什麼?

我的問題是:如何將它存儲在一個文件中,比如「DB.txt」,然後我可以在我的JavaScript程序中重新使用它?

編輯:好像我是個白癡,而且「最簡單」的方式爲我做這只是創建另一個JavaScript文件,我只是創建用我所有的值的數組。謝謝大家 !

+0

我會使用[索引資料](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) –

+0

有沒有辦法做到這一點無需外部API? – Squiller

+1

IndexedDB不是外部API,它是WebAPI的一部分,在大多數瀏覽器(至少是最新版本)中本地實現。 – mdziekon

回答

1

如果你想避免使用類似索引資料(如A.Wolff建議)小DB的,你可以創建一個文本文件,然後通過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 
}); 
相關問題