[英]Read variables from a file in Javascript
我在Javascript中有一个名为words
的变量,如下所示:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]
并且我将可变元素用作例如words[0].url
,它指向第一个URL,即http://google.com/
等。
如果我将数据存储在这样的文件中(我称其为file.csv):
This, http://google.com/
is, http://bing.com/
some, http://somewhere.com/
random, http://random.org/
text, http://text.com/
InCoMobi, http://incomobi.com/
Yahoo, http://yahoo.com/
Minutify, http://minutify.com/
如何使用Javascrip读取文件并重新创建可变words
,其格式与前面提到的完全相同,即重新创建:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]
看来有两个步骤。 首先是获取外部文件,然后下一步是将其转换为所需的格式。
如果您不使用jQuery,则第一步是:
var file = new XMLHttpRequest();
file.onload = function() {
alert(file.responseText);
}
file.open('GET', 'file.csv');
file.send();
下一步是获取该file.responseText并将其格式化。 我可以这样做:
var file = new XMLHttpRequest();
var words = [];
file.onload = function() {
var lines = file.responseText.split("\n");
for (var i = 0; i < lines.length; i++) {
var word = {};
var attributes = lines[i].split(",");
word.text = attributes[0];
word.url = attributes[1];
words.push(word);
}
}
file.open('GET', 'file.csv');
file.send();
如果您使用的是JSON文件,只需将上面的函数更改为:
file.onload = function() {
words = JSON.parse(file.responseText);
}
请记住,在onload函数运行之前,words变量将不可用,因此您应该将其发送给使用它的另一个函数。
您可以使用fetch API
,它具有许多优点,其中之一就是语法很短,这与XMLHttpRequest
构造函数不同。
fetch("object.json").then(function(data){window.data=data.json()}); //then access the data via [window.data]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.