2016-10-13 2 views
0

Die Logik:GET-Funktion Konsole Fehler

my_function schaut durch datei.txt, wenn sie das Wort „Hallo“ findet, gibt wahr. Wenn nicht, falsch.

Das Problem:

Uncaught Typ Fehler: contents.includes ist keine Funktion

Einschränkungen:

nur einfachen Javascript-

function my_function() { 
var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function(contents) { 
if (this.readyState == 4 && this.status == 200) { 
//contents variable now contains the contents of the textfile as string 

//check if text file contains the word Hello 
var hasString = contents.includes("Hello"); 

//outputs true if contained, else false 
console.log(hasString); 

} 
}; 
xhttp.open("GET", "http://www.example.com/file.txt", true); 
xhttp.send(); 
} 
+0

@Tushar Wenn ich enthält() mit jquery GET-Funktion arbeitet. – Malasorte

+0

Versuchen Sie 'var hasString = contents.indexOf (" Hello ")> -1;' Überprüfen Sie auch, ob 'includes' in Ihrem Browser unterstützt wird. – Tushar

+0

Sie müssen überprüfen, ob der "Inhalt" nicht leer ist/undefiniert hinzufügen: var hasString; if (Inhalt! == undefined && contents! == "") { hasString = contents.includes ("Hello"); } Stellen Sie sicher, dass das zurückkommende Ergebnis nicht leer ist. Die Überprüfung des Status ist in diesem Zusammenhang nicht ausreichend. –

Antwort

1

verwenden diese verwenden können .responseText anstelle des Parameters
this.responseText ist die Antwort des Ajax

function my_function() { 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      //contents variable now contains the contents of the textfile as string 

      //check if text file contains the word Hello 
      var hasString = this.responseText.includes("Hello"); 

      //outputs true if contained, else false 
      console.log(hasString); 

     } 
    }; 
    xhttp.open("GET", "http://www.example.com/file.txt", true); 
    xhttp.send(); 
} 
+0

Funktioniert! Vielen Dank! – Malasorte