检查文本文件是否包含带有javascript的内容

Check if text file contains something with javascript?

本文关键字:javascript 包含带 文本 文件 是否 检查      更新时间:2023-09-26

如何检查服务器上的文件是否包含特定文本?到目前为止,这就是我所做的:

<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$.get('myfile.txt', function(data) {
   if (data == "Hello World") {
    alert("Hello World is found");
   }
   else {
    alert("It's NOT found");
   }
}, 'text');
</script>

这是myfile.txt

Blah blah blah
It's a good day.
Have a nice day everyone.
Hello World.

即使文件包含Hello World该脚本也会不断返回It's NOT found 我该如何解决这个问题?

更新:这个答案有效,但现在我想用setInterval每秒检查一次,但在我摆脱Hello World后它不起作用myfile.txt即使它不再存在,它仍然显示Hello World is found。这是我所做的:

<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.get('myfile.txt', function(data) {
   if (data.indexOf("Hello World")>-1){
    document.write("Hello World is found");
   }
   else {
    document.write("It's NOT found");
   }
}, 'text');}, 1000);
</script>

更新2:这是我对@Stuart答案的回应的代码

setInterval(function() {
    $.ajax({
        cache:false,
        $.get("myfile.txt"
            success: function(result) {
                if (result.indexOf("Hello World")>-1){
                    document.write("Hello World is found");
                }
                else {
                    document.write("It's NOT found");
                }
            }
        )
    })
});

在我的控制台上,它说:

Uncaught SyntaxError: Unexpected token .

我该如何解决这个问题?对不起,我还在学习Javascript

更新 3:

<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.get('myfile.txt',{cache:false} function(data) {
   if (data.indexOf("Hello World")>-1){
    document.write("Hello World is found");
   }
   else {
    document.write("It's NOT found");
   }
}, 'text');}, 1000);
</script>

我在控制台中得到这个:Uncaught SyntaxError: missing ) after argument list,我的浏览器没有显示任何内容。

您正在检查整个文本是否等于字符串"Hello world"。

使用 String.indexOf,如下所示:

$.get('myfile.txt', function(data) {
   if (data.indexOf("Hello world") !== -1) {
   alert("Hello World is found");
   }
   else {
    alert("It's NOT found");
   }
}, 'text');

顺便说一下,javascript的黄金法则:控制台.log一切。然后,您将了解结构和jQuery创建响应对象的方式,例如,在尝试调试时不要使用alert。

使用 indexOf 而不是 ==。您正在测试整个文本是否等于hello world。

if (textdata.indexOf(stringToFind)>-1){ do stuff } 

编辑,问题已变形,代码示例:

function getTextfile()
{
  $.get('myfile.txt', {cache:false}, function(data) 
  {
    if (data.indexOf("Hello World")>-1) {
      document.write("Hello World is found");
    }
    else {
      document.write("It's NOT found");
    } 
    setTimeout(getTextfile, 1000);
 });
} 
getTextfile();