2016-09-17 62 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 
}); 
相关问题