link 文件到 Javascript 程序的最简单方法是什么?
What's the easiest way to link a file to a Javascript program?
我目前正在制作一些离线 html 工具,我需要使用一个很长的对象列表,我已经将它们存储在一个数组中,但它太大了,无法存储在我原来的 javascript 文件.
我的问题是:如何将其存储在一个文件中,例如 "DB.txt" 然后我可以在我的 javascript 程序中重复使用?
编辑:看来我很愚蠢,"easiest" 我这样做的方法只是创建另一个 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
});
我目前正在制作一些离线 html 工具,我需要使用一个很长的对象列表,我已经将它们存储在一个数组中,但它太大了,无法存储在我原来的 javascript 文件.
我的问题是:如何将其存储在一个文件中,例如 "DB.txt" 然后我可以在我的 javascript 程序中重复使用?
编辑:看来我很愚蠢,"easiest" 我这样做的方法只是创建另一个 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
});