用Javascript读取外部文件 [英] read external file with Javascript
问题描述
我有一个名为 profiles.txt 的外部文本文件,其中包含以下格式的信息:
杰森/红/暴龙
扎克/黑/乳齿象
比利/蓝/三角龙
特尼/黄/格里芬
(等)
如何使用JavaScript读取文件以输出以下HTML:
姓名:Jason< br>
颜色:红色< br>
头像:暴龙< br>
< br>
名称:Zack< br>
颜色:黑色< br>
头像:Mastodon< br>
< br>
(etc)
解决方案var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET',test.txt,false);
xmlhttp.send();
document.write(xmlhttp.responseText.split('\r\\\
')。map(function(i){return i.replace(/(.+),(.+),(.+ )/ g,'Name:$ 1< br> Color:$ 2< br> Avatar:$ 3< br>')}).join('< br />'));
Array.map 。此外,IE使用
新的ActiveXObject(Msxml2.XMLHTTP)
这是一个非常简单的例子。我使用asyc false这是不好的,document.write是不好的。但我只是想演示如何获取文件并解析输入。I have an external textfile of variable length named profiles.txt with information in the following format:
Jason/Red/Tyrannosaurus Zack/Black/Mastodon Billy/Blue/Triceratops Trini/Yellow/Griffin (etc)
How can I read through the file using JavaScript to output the following HTML:
Name: Jason<br> Color: Red<br> Avatar: Tyrannosaurus<br> <br> Name: Zack<br> Color: Black<br> Avatar: Mastodon<br> <br> (etc)
解决方案Here's an example using XMLHttpRequest:
var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open('GET', "test.txt", false); xmlhttp.send(); document.write(xmlhttp.responseText.split('\r\n').map(function (i) {return i.replace(/(.+),(.+),(.+)/g, 'Name: $1<br>Color: $2<br>Avatar: $3<br>')} ).join('<br/>'));
Array.map needs to be shim in IE8 and below. Also, IE uses
new ActiveXObject("Msxml2.XMLHTTP")
This is a very slimmed down example. I'm using asyc false which is bad and document.write which is bad. But I just wanted to demonstrate getting the file and parsing the input.这篇关于用Javascript读取外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!