如何通过Javascript获取URL响应



我正试图使用javascript通过URL获取响应,但readystate ab=nd状态分别没有得到4和200。当Url被直接获取时,它是工作的,而不是通过代码。

!<DOCTYPE html>
<html>
<body>
<head>
<script>    
var Http = new XMLHttpRequest();
document.write("1");
var url='http://10.64.10.222:5000/';
document.write("2");
Http.open("GET",url);
document.write("3");
Http.send();
document.write("4");
document.write(Http.readyState);
document.write(Http.status);
Http.onreadystatechange = function(){
if(Http.readyState == 4 && Http.status == 200 ){
document.write("6");
document.write(Http.responseText);
}
document.write("5");
}  
</script>
</head>
</body>
</html>

为什么使用传统和旧的XMLHttpRequest,使用最新的Fetch API。取自MDN

Fetch API提供了一个获取资源的接口(包括通过网络(。它对任何使用过的人来说都很熟悉XMLHttpRequest,但它提供了一个更强大、更灵活的特性集。

演示片段如下,有许多选项可以将标题和状态代码读取为wll。

fetch('http://10.64.10.222:5000/')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});