我在文本文件中放了一个JSON字符串。 现在我想读取此文件,以便使用Javascript将字符串传输到对象。
如何阅读文件?
答案 0 :(得分:0)
如果你想在客户端上这样做,你可以使用HTML5文件api。以下是一些示例代码,可以帮助您入门。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body
{
font-size:18pt;
}
</style>
<script type="text/javascript">
function init() {
var bHaveFileAPI = (window.File && window.FileReader);
if (!bHaveFileAPI) {
alert("This browser doesn't support the File API");
return;
}
document.getElementById("fileElem").addEventListener("change", onFileChanged);
}
function onFileChanged(theEvt) {
var thefile = theEvt.target.files[0];
// check to see if it is text
if (thefile.type != "text/plain") {
document.getElementById('filecontents').innerHTML = "No text file chosen";
return;// this will just get out of the function.
}
var reader = new FileReader();
//file reader has an event there is no need to assign an event listener the
//onload event can just be assign like the below.
reader.onload = function (evt) {
var resultText = evt.target.result;
document.getElementById('filecontents').innerHTML = resultText;
}
// readAsText is a native method of the FileReader object.
reader.readAsText(thefile);
}
window.addEventListener("load", init);
</script>
</head>
<body>
<h1>Reading File Data as Text</h1>
<form action="">
<label>Select a file: </label>
<input type="file" name="files" id="fileElem" />
</form>
<p>File contents: </p>
<textarea cols="80" rows="10" id="filecontents"></textarea>
</body>
</html>
这只适用于firefox和chrome,因为它们是唯一一次支持文件API,否则如果文件在服务器上就可以发出http请求。
答案 1 :(得分:-1)
使用XMLHttpRequest
(又称AJAX调用)将文件加载到JavaScript中。