2014-04-19 113 views
0

我有一个在Javascript称为words这样的变量:从文件中读取变量在Javascript

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该文件并重新-C reate变量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/"}] 
+1

为什么不保存在JSON而不是CSV内容? – meagar

+0

当然,我可以这样做。但是,那么如何阅读和创建“单词”呢? – TJ1

回答

0

它看起来像有两个步骤。首先是获取外部文件,下一步是将其转换为您想要的格式。

如果你不使用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功能运行,所以你应该把它发送给另一个使用它的函数。

+0

谢谢,根据以前的建议我创建了一个JSON文件。现在是更容易阅读文件?你能帮我读一下JSON文件并用文字存储结果吗? – TJ1

+0

当然,如果你喜欢答案,确保你'接受'它:)答案已更新。 –

+0

我试着用你的代码,但不幸的是它没有工作:( – TJ1

0

您可以使用fetch API,它具有很多优点,其中一个是非常简短的语法,不像XMLHttpRequest构造函数。

fetch("object.json").then(function(data){window.data=data.json()}); 
 
//then access the data via [window.data]