[英]Reading values from text file using javascript
誰能給我JavaScript函數來實現這一目標。
您應該在問題中指定要讀取客戶端文件,因為我看到很多內容都涉及服務器端讀取。
您應該看一下FileAPI-一種HTML 5 Javascript附加功能,它允許JavaScript通過文件輸入讀取文件內容。
我正在為您編寫代碼示例-但是您應該閱讀這里是一個不錯的網站
如果沒有FileAPI,您仍然可以使用帶有target =“ some iframe”形式的文件輸入字段-然后讓服務器上傳文件並返回文本。 (FormData允許在Ajax中上傳文件,但並非所有瀏覽器都支持它)。
因此,File API是您的理想之路以下是使用File API的方法
<input type="file"/>
<script>
$(function(){
$("input").change(function(e){
console.log(["file changed",e]);
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(["this is the contents of the file",e.target.result]);
};
reader.readAsText(myFile)
});
}
)
</script>
您還可以實現拖放界面(例如google gmail has)
$("div").on("dragover",function(e){
e.dataTransfer = e.originalEvent.dataTransfer;
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}).on("drop",function(e){
e.dataTransfer = e.originalEvent.dataTransfer;
e.stopPropagation();
e.preventDefault();
console.log(["selected files", e.dataTransfer.files])});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.