检查文本文件是否包含javascript内容?

时间:2016-03-12 23:53:37

标签: javascript

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

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

即使文件包含It's NOT found,该脚本也会一直返回Hello World。我该如何修复?

更新 这个答案有效,但现在我想用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我的浏览器没有显示任何内容。

2 个答案:

答案 0 :(得分:1)

使用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();

答案 1 :(得分:1)

您正在检查整个文本是否等于字符串&#34; Hello world&#34;。

使用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的黄金法则:console.log应有尽有。然后,您将了解jQuery的结构和方式,例如,在尝试调试时,不要使用警报。

相关问题