您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

如何逐行读取txt文本?

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 如何逐行读取txt文本?Ajax可以实现么

想要读取分行txt文件,并在每行前后添加内容。

如txt文件内容是这样的

http://www.baidu.com/

http://www.google.com.hk/

我想最终输出的结果是

<a href="http://www.baidu.com/"><img src="1.jpg" /></a>
<a href="http://www.google.com.hk/"><img src="2.jpg" /></a>

就是这样遍历…请问怎样实现?

我在W3School找到一段代码,直接读取txt文件的,不能添加前后缀。

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","/ajax/test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">通过 AJAX 改变内容</button>

</body>
</html>

求大神相助,谢谢。


解决方案:

 

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","/ajax/test1.txt",false);
xmlhttp.send();
var i=1;
document.getElementById("myDiv").innerHTML=xmlhttp.responseText.replace(/.+/g,function(url){
  return '<a href="'+ url +'"><img src="'+ i++ +'.jpg" /></a>'
})
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">通过 AJAX 改变内容</button>

</body>
</html>