javascript - GET函数控制台错误

标签 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();
}

最佳答案

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

关于javascript - GET函数控制台错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011687/

相关文章:

jquery - 使用 jquery 在列表框中选择全部或取消选择全部?

javascript - ajax 请求不使用 jQuery 发送任何数据 ASP.NET MVC 项目

javascript - jQuery 表达式 $ ('a[href*=#]:not([href=#])' ) 针对哪些元素?

javascript - 通过透明 div 传递点击和 jQuery 悬停的困境

javascript - $.extend() = 与服务器循环一起使用时不扩展

javascript - 使用 jquery ajax 和地理定位解析 xml

jquery - Primefaces 6.0 对话框架和框架集

javascript - 在繁忙的 JavaScript 代码期间页面未更新

javascript - 数据过滤 React Highcharts

javascript - jQuery 让 div 在点击时具有相同的高度