简体   繁体   English

如何从外部文件(如.txt)正确将数据加载到Javascript数组

[英]How to correctly load data to Javascript's Array from external file (like .txt)

I want to load some data to the page using Javascript. 我想使用Javascript将一些数据加载到页面上。

The easiest way for me is to use js Array, like below: 对我而言,最简单的方法是使用js Array,如下所示:

phones = ["14 211 122", "11 212 131", "666 132 123"];

But I feel that I shouldn't keep this kind of data in .js file. 但是我觉得我不应该将这种数据保存在.js文件中。 I think it should be in a separate, easier to access and edit file like .txt. 我认为它应该位于单独的,更易于访问和编辑的文件中,例如.txt。

On the other hand, I'm not sure if loading data from .txt will be secure? 另一方面,我不确定从.txt加载数据是否安全?

What should I use? 我应该使用什么? Some kind of jQuery .load()? 某种jQuery .load()? What do you suggest? 你有什么建议?

Thanks for help! 感谢帮助!

You can use something like : 您可以使用类似:

var data;
$.ajax({url: 'values.txt'}).done(function(d) { 
    //assuming values.txt is formatted like : 1,2,3,4,5,6;
    data = JSON.parse('[' + d + ']');
});

However I'd recommend just storing the javascript directly instead of having to reparse it like that. 但是我建议只直接存储javascript,而不必像这样重新解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM