将.txt文件加载到文本区域Javascript中



我试图将文本文件放入文本区域。结果是"http://mywebsite.com/textfile/(txtinput(.txt并且文本文件不会加载到文本区域中。

<html>
   <head>
      <title>textbox</title>
      <script type="text/javascript">
         function readBOX() {
            var txtinput = document.getElementById('txtinput').value;
            document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
         }
      </script>
   </head>
   <body>
      <p> Type</p>
      <input type="text" id="txtinput" />
      <input id="open" type="button" value="READ" onClick="readBOX()" />
      <form>
         <textarea name="text" rows="20" cols="70">loaded text here</textarea>
      </form>
   </body>
</html>

你必须使用类似它张贴在这个答案中的东西

jQuery

$(document).ready(function() {
   $("#open").click(function() {
       $.ajax({
           url : "helloworld.txt",
           dataType: "text",
           success : function (data) {
               $("#text").text(data);
           }
       });
   });
}); 

阅读更多关于 .ajax(( 的 jQuery 文档

非 jQuery

我不想使用 jQuery,你必须使用 XMLHttpRequest -Object 这样的东西:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;

但这可以在此处的SO-Answer或维基百科上完整且易于理解的文档上阅读

注意:但这不跨浏览器兼容,对于较旧的IE版本,您必须使用ActiveXObject("Microsoft.XMLHTTP")对象

谢谢大家。Javascript对我不起作用。我改用了PHP,它运行得很好。

<!DOCTYPE HTML>
<html>
   <head>
      <title>textbox</title>
   </head>
   <body>
<form action="process.php" method="post">
      <input type="text" name="name" />
      <input type="submit" />
</form>
   </body>
</html>

过程.php

<textarea name="text" rows="20" cols="70"> 
<?php $name =  $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
这就是

我将文本加载到文本区域的方式

Main.css
.textbox{
         font-size: 12px;
         float  : left;
         height : 197px;
         width : 650px; }

Default.html
<!DOCTYPE html>
<html> 
    <head>
        <!-- Charactor set allowed to use -->
        <meta charset="utf-8"/>
        <title>Text from .txt file to TextArea</title>
        <!-- External stylesheet -->
        <link rel="stylesheet" href="main.css" />
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
       <textarea class="textbox" id="Brief" readonly></textarea>
       <script> $( "#Brief" ).load( "text.txt" ); </script>
    </body> 
</html>

谷歌文本区域查找文本区域的格式

最简单的方法之一是请求服务器返回预填充的文本区域(下面是一个使用 PHP 的示例(:

<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>

注意:任何服务器端脚本语言都可以执行类似的操作。

同时,如果您需要动态加载它,最好的办法是使用 AJAX 方法。选择最适合您编码和维护的方法。虽然jQuery是一种流行的方法,但你可以自由地使用任何你觉得舒适的方法,并且可能想先了解XmlHttpRequest。

使用 Pure JavaScript 的动态 AJAX 请求可能很棘手,因此请确保您的解决方案是跨浏览器的。一个常见的错误是直接使用 XmlHtpRequest 并且无法使其与较旧的 IE 版本兼容,这会导致随机错误,具体取决于您使用的浏览器/版本。例如,它可能看起来像这样(需要在所有目标浏览器上进行测试,以便您可以根据需要添加回退(:

纯JS:

if (typeof XMLHttpRequest === "undefined") {
    XMLHttpRequest = function () {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
        catch (e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
        catch (e) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (e) {}
        throw new Error("This browser does not support XMLHttpRequest.");
    };
}
function readBOX() {
    function reqListener () {
        document.forms[0].text.value = this.responseText;
    }
    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
    var oReq = new XMLHttpRequest();
    oReq.onload = reqListener;
    oReq.open("get", filePath, true);
    oReq.send();
}

但是如果你不介意牺牲一些性能来确保最大的支持,你应该使用 jQuery 的实现:

j查询:

function readBOX() {
    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
    $.ajax({
        url: filePath
    }).done(function(data){
        document.forms[0].text.value = data;
    });
}

注意:jQuery的库有点大,但请记住,如果你直接从谷歌服务器包含它,你的用户很可能已经在缓存中了它。

希望这对:)有所帮助

window.addEventListener('DOMContentLoaded', (e) => {
    let input = document.getElementById('input');
    
    // load default.txt into input box
    try {
        let fileToLoad = './default.txt';
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open('GET', fileToLoad, false);
        xmlhttp.send();
        input.innerHTML = xmlhttp.responseText;
    } catch(DOMException) {
        input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
    }
});

最新更新