如果你想避免使用类似索引资料(如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
});
我会使用[索引资料](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) –
有没有办法做到这一点无需外部API? – Squiller
IndexedDB不是外部API,它是WebAPI的一部分,在大多数浏览器(至少是最新版本)中本地实现。 – mdziekon