Html 将 .txt 文件加载到 textarea Javascript 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19020484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:47:37  来源:igfitidea点击:

Loading .txt file into textarea Javascript?

javascripthtml

提问by Gwa Si

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txtand the text file doesn't load into textarea.

我试图将文本文件放入 textarea。结果是“ http://mywebsite.com/textfile/(txtinput).txt并且文本文件没有加载到 textarea 中。

<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>

采纳答案by Gwa Si

Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.

谢谢大家。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>

Process.php

进程.php

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

回答by Martin

You have to use something like its posted in this Answer

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

jQuery

jQuery

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

Read more on the jQuery Documentation of .ajax()

阅读有关.ajax()jQuery 文档的更多信息

Non jQuery

非 jQuery

I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:

我你不想使用 jQuery 你必须使用XMLHttpRequest-Object 类似的东西:

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

But this can be read on the SO-Answer hereor the complete and understandable documentation on Wikipedia

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

Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP")object

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

回答by Sha1962 Development

This is how I load text into a textarea

这就是我将文本加载到 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>

google textarea to find format of text area

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

回答by Frederik.L

One of the easiest way is to request the server to return the pre-filled textarea (Here's an example using PHP):

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

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

Note: Something similar can be done with any server-side scripting language.

注意:任何服务器端脚本语言都可以做类似的事情。

In the meantime, if you need to load it dynamically, your best bet is using an AJAXapproach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequestfirst.

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

Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):

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

Pure JS:

纯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();
}

But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:

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

jQuery:

jQuery:

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;
    });
}

Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.

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

Hope this helps :)

希望这可以帮助 :)