![](/img/trans.png)
[英]Using Javascript / Jquery to change text in div upon button click
[英]Read and display the text file contents upon click of button using Javascript
单击名为result的按钮后,我想使用 Javascript 函数读取并显示一个文本文件(存在于我的本地驱动器位置,例如: C:\\test.txt )并以 HTML 文本显示 test.txt 文件内容区域。
我是 Javascript 的新手,有人可以建议 Javascript 函数的代码来读取和显示 .txt 文件的内容吗?
出于安全原因,对本地文件的 Ajax 请求将失败。
想象一下,一个网站按照您的要求访问您计算机上的文件,但没有让您知道,并将内容发送给黑客。 你不会想要这样的,浏览器制造商会照顾到这一点来保护你的安全!
要读取硬盘驱动器上文件的内容,您需要有一个<input type="file">
并让用户自己选择文件。 你不需要上传它。 你可以这样做:
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
使用 $.ajax() 函数: http : //api.jquery.com/jQuery.ajax/
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
正如您提到的 HTML,我假设您想在浏览器中执行此操作; 那么在浏览器中访问本地文件的唯一方法是使用文件 API,并且只能通过用户的操作来获取文件,例如在 <input type='file'> 元素中选择文件或拖放文件在您的页面中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.