简体   繁体   中英

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

I need to load the text file data into a javascript array and define a dynamic form using html.

I tried below code for extracting data from text file and to store in a javascript array and it works as long as it is in .js file

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

but when I embed it inside my html file this doesn't work.

below is my html code. for now I am just forming an array with months but i need to replace it with array taken from the text file.

<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>

I gave the 3 line code which is working independently as a .js file inside addOption_list function in above code and it doesn't work. Appreciate help on this.

Thanks in advance

The FileSytem (fs) module is for NodeJS applications so needs to be in .js file. If you want to load the file into your html you can use Ajax instead. This may work:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM