2016-06-10 42 views
-1

現在我有具有嵌入的Javascript代碼的網頁,其定義了下面的數組:如何將我的Javascript代碼中的服務器上的文本文件的內容放入數組中?

var words = [ "apple", "banana", "orange" ]; 

該陣列然後被饋送到在網頁的HTML部分的一些輸出。我想要做的是創建一個名爲「words.txt」的文本文件,其內容可以放入數組中,而不是在代碼中硬編碼數組的內容。 文本文件應該是這樣的:

apple, banana, orange 

我該怎麼辦呢?

+0

要讀取和寫入.txt文件嗎? – HudsonPH

回答

2

更好的保留文件JS:

[words.js] 
var words = ['apple', 'banana', 'orange']; 

[index.html] 
<script src="words.js"></script> 
<script> 
    alert(words[0]); 
</script> 

如果使用像一些用PHP服務器端語言,你可以讀取文件內容直接向JS變量:

[words.txt] 
apple, banana, orange 

[index.php] 
$words = file_get_contents('words.txt'); 

$words = preg_replace("/(\w+)/g", '"$1"', $words); // add quotes around words. 

?> 
<script> 
    var words = [<?= $words; ?>]; 

    alert(words[0]); 
</script> 
+0

使用'json_encode()'而不是自己添加引號會更好。 – Barmar

+0

@Barmar這將是,但是OP想要的文件格式與'string,string,string'一樣普通,而不是'{「string」,「string」,「string」}'。 – Justinas

+0

'json_encode'會像你一樣創建'[「string」,「string」,「string」]''。 – Barmar

0

使用AJAX閱讀來自服務器的文件。以下是如何使用jQuery來做到這一點。如果你想使用普通的JS,你需要將它翻譯成等效的代碼。

var words = []; 
$.get("words.txt", function(data) { 
    words = data.split(', '); 
    // update webpage with words 
}); 
相關問題