GET功能控制台错误

时间:2016-10-13 03:13:13

标签: javascript jquery ajax

逻辑:

my_function查看file.txt,如果找到单词“Hello”,则返回true。如果不是,那就是假。

问题:

未捕获类型错误:contents.includes不是函数

限制:

只能使用普通的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();
}

1 个答案:

答案 0 :(得分:1)

使用this.responseText而不是参数内容
this.responseText是你的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();
}