【问题标题】:How to read a .txt file and convert to string in javascript? [duplicate]如何读取 .txt 文件并在 javascript 中转换为字符串? [复制]
【发布时间】:2019-04-22 04:10:07
【问题描述】:

我正在尝试使用 javascript 来读取 .txt 文件,但我似乎无法在线找到任何方法。该代码的目的是扫描文本文件中的某个字符串。在我的代码中,用户故意上传文件并将其存储在一个变量中,但我找不到一种方法来实际读取文件中的文本并将其转换为字符串。任何帮助将不胜感激,谢谢。

    document.getElementById("answer").addEventListener(search);
    document.getElementById("actualAns").addEventListener(search); 

    function myFunction() {
        var targetAns = document.getElementById("answer").value; //the user inputs a .txt file
        var actualAns = document.getElementById("actualAns").value; //the user enters the string they want to search
        var n = actualAns.search(targetAns); // this part does not work, it should search the text file but it only searches the name
        if(n > -1) {
          document.getElementById("result").innerHTML = "Correct";
        } else {
          document.getElementById("result").innerHTML = "Incorrect";
        }
    }

【问题讨论】:

    标签: javascript jquery html text


    【解决方案1】:

    你可以这样读取文件:

    function readFile() {
    
      jQuery.get("file.txt", function(textString)) {
    
      //do what you want with the textString
    
      });
    }
    

    在 textString 中,您的文件中将包含文本字符串。

    【讨论】:

    • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接。如果没有围绕它们的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案 - From Review
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2015-12-03
    • 1970-01-01
    • 2017-09-20
    相关资源
    最近更新 更多