从 XMLHttprequest 获取数据

get data from XMLHttprequest

我想获取 json 格式的数据。 我已经输入了这段代码,但它没有 return 任何内容。 我的代码哪里出了问题?!!

<script language="JavaScript">
var xmlhttp = new XMLHttpRequest();

var url = "http://codeforces.com/api/contest.list?gym=true";


xmlhttp.onreadystatechange = myfunction;

xmlhttp.open("GET", url, true);

xmlhttp.send(null);


function myfunction() {

if (XMLHttp.readyState == 0) {
window.alert("Uninitialized");
}
if (XMLHttp.readyState == 1) {
window.alert("loading");
}
if (XMLHttp.readyState == 2) {
window.alert("loaded");
}
if (XMLHttp.readyState == 3) {
window.alert("waiting");
}
if (XMLHttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}


</script>

在 html 代码中,我有一个 div id = "id01"

试试这个:

xmlhttp.onload = function() {
  if (xmlhttp.status >= 200 && xmlhttp.status < 400) {
    // Success!
    var data = JSON.parse(xmlhttp.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

免责声明:我从 http://youmightnotneedjquery.com/#json

中获取了这段代码

请记住 javascript 区分大小写。

编辑为:

var xmlhttp = new XMLHttpRequest();

var url = "http://codeforces.com/api/contest.list?gym=true";


xmlhttp.onreadystatechange = myfunction;

xmlhttp.open("GET", url, true);

xmlhttp.send(null);


function myfunction() {

if (xmlhttp.readyState == 0) {
window.alert("Uninitialized");
}
if (xmlhttp.readyState == 1) {
window.alert("loading");
}
if (xmlhttp.readyState == 2) {
window.alert("loaded");
}
if (xmlhttp.readyState == 3) {
window.alert("waiting");
}
if (xmlhttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}

只需使用fetch。它是现代的 XMLHttpRequest。

const url = "http://codeforces.com/api/contest.list?gym=true";
fetch(url)
    .then(
        response => response.json() // .text(), etc.
        // same as function(response) {return response.json();}
    ).then(
        jsonString => {
            const json = JSON.parse(jsonString);
            document.getElementById("id01").innerHTML = json[1].id;
        }
    );

更多信息:

Mozilla Documentation

Can I Use (75% Aug 2017)

Matt Walsh Tutorial