使用javascript从文本文件中提取数据

Extracting data from text file using javascript

本文关键字:提取 数据 文件 文本 javascript 使用      更新时间:2023-09-26

如何使用javascript从文本文件中提取文本数据?我正在制作一部在线词典。我会写HTML和CSS,但不会写javascript。

Word将在第一个文本框中输入,然后单击搜索按钮,结果将显示在底部文本框中。文本文件中的数据就像"苹果|多汁的水果"(没有引号)现在我想在搜索字段中的文本检查单词之前的"|"标志,如果匹配是找到单词/单词后"|"将被发送到结果字段。我如何使用javascript做到这一点?

我的项目的HTML代码如下:

<html>
  <head>
    <title>Online Dictionary</title>
    <style>
      .field{
        border: 2px solid black;
      }
      #result_field{
        margin-top: 5px;
        width: 247px;
        height: 100px;
      }
    </style>
  </head>
  <body>
    <input type="text" placeholder="Enter your word here..." name="search_field" id="search_field" class="field">
    <input type="button" value="SEARCH" name="btn" id="btn" class="btn"> <br>
    <input type="text" placeholder="Meaning here..." name="result_field" id="result_field" class="field">
  </body>
</html>

尝试使用Ajax。

Ajax是从服务器向文件发出请求,所以有了它,你可以:

  • 检查用户网络速度;
  • 获取文件内容

我编写了几个简单的函数,你可以在这里查看。

要使用上面的函数之一,您可以添加这样的行:

$GET('file.txt?c=0',function(result){/* Success function */},function(e){/* Error function */});
$GET('dictionary.txt?anyvalue=0',function(text){alert(text);},function(e){/* Error function */});
/* in ahead of the link you will have to include the ?urlvar=value to the function works, */
/*     I still didn't leave the function complete */

注意:如果你想从另一个服务器请求一个文件,那么该文件必须允许服务器访问它(允许或不允许,你可以使用PHP或htaccess)。

正如@Stephan Bijzitter所说,你可以使用PHP(或ASP) -在那里你可以很容易地得到一个词的正确含义。

例如:

if($_GET['word']=="PC"){echo "Meaning";}
switch($_GET['word']){case "Word":echo "A word?";break;}
/* In PHP, $_GET['word'] returns the value of a parameter in page URL called "word" */