簡體   English   中英

我能夠將文本數據加載到.js文件中的javascript數組中,但不能加載到html中

[英]I am able to load text data into a javascript array in .js file but not inside html

我需要將文本文件數據加載到javascript數組中,並使用html定義動態表單。

我嘗試下面的代碼從文本文件中提取數據並存儲在javascript數組中,只要它在.js文件中就可以工作

var fs = require('fs');
var textByLine = fs.readFileSync('123.txt').toString().split("\n");
console.log(textByLine);

但是當我將它嵌入我的html文件中時,這不起作用。

下面是我的HTML代碼。 現在我只是用數月形成一個數組,但我需要用從文本文件中取出的數組替換它。

<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">


<script language="javascript">
var dt=new Date();
var dt_month=dt.getMonth() +1;
//alert(dt_month);
function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function addOption_list(){
var month = new Array("January","February","March","April","May","June","July","August",
"September","October","November","December");
for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
document.drop_list.Month_list.options[i].selected=true;
}
}
</script>
</head>

<body onLoad="addOption_list()";>
You can see the view-> Source of this page. 
<br><br>
<FORM name="drop_list" action="yourpage.php" method="POST" >

<SELECT  NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>


</body>
</html>

我給出了3行代碼,它在上面代碼中的addOption_list函數中獨立地作為.js文件工作,它不起作用。 感謝您的幫助。

提前致謝

FileSytem(fs)模塊用於NodeJS應用程序,因此需要在.js文件中。 如果要將文件加載到html中,可以使用Ajax。 這可能有效:

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this.responseText);
    }
  };
  xhttp.open("GET", "123.txt", true);
  xhttp.send();
}

function myFunction(data) {
  var textByLine = data.split("\n");
  console.log(textByLine);
}

loadDoc();

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM