逻辑:
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/