现象:
- ajax读取一个本地文本文件,Chrome控制台报错:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/
虽然这只是一个警告,并不影响程序执行,但看上去着实很烦人。
原本的代码如下:
let xhr = new XMLHttpRequest();
xhr.open(
"GET",
"/static/test.txt",
false
);
xhr.overrideMimeType("text/html;charset=utf-8"); //默认为utf-8
xhr.send(null);
console.log(xhr.responseText)
这个问题也不仅限于读取本地文件,网上搞讨论的人也比较多,我试了很多未果。
解决:
- 后来改用axios取代原生的XMLHttpRequest,嘿嘿,果然,问题解决了。
- 代码如下,换用这段代码后,控制台不再出现那个警告:
this.axios({
url: "/static/test.txt", baseURL: "" }).then(
(response) => {
if (response.data) {
console.log(response.data);
}
}
);
},
后级:
- 关于这个问题的成因,可以参考这篇文章(但他的方案没有解决我的问题):
关于chrome控制台警告:Synchronous XMLHttpRequest on the main thread终极解决办法(解决不了看红色字体) - 关于为什么换成axios就解决了,我没有深究,原因不明。