2014-04-19 174 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]