[英]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.