Javascript 从XMLHttprequest获取数据

Javascript 从XMLHttprequest获取数据,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我想获取json格式的数据。 我已经输入了这段代码,但它没有返回任何内容。 我的代码哪里出了问题 <script language="JavaScript"> var xmlhttp = new XMLHttpRequest(); var url = "http://codeforces.com/api/contest.list?gym=true"; xmlhttp.onreadystatechange = myfunction; xmlhttp.open("GET", ur

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

<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>

var xmlhttp=new XMLHttpRequest();
变量url=”http://codeforces.com/api/contest.list?gym=true";
xmlhttp.onreadystatechange=myfunction;
open(“GET”,url,true);
xmlhttp.send(空);
函数myfunction(){
if(XMLHttp.readyState==0){
窗口警报(“未初始化”);
}
if(XMLHttp.readyState==1){
窗口警报(“加载”);
}
if(XMLHttp.readyState==2){
窗口警报(“已加载”);
}
if(XMLHttp.readyState==3){
窗口。警报(“等待”);
}
if(XMLHttp.readyState==4){
窗口。警报(“完成”);
var y=JSON.parse(xmlhttp.responseText);
document.getElementById(“id01”).innerHTML=y[1].id;
}
}
在html代码中,我有一个id=“id01”的div

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

  }
};
xmlhttp.onload=function(){
如果(xmlhttp.status>=200&&xmlhttp.status<400){
//成功!
var data=JSON.parse(xmlhttp.responseText);
}否则{
//我们到达了目标服务器,但它返回了一个错误
}
};

免责声明:我从

中获取了这段代码,请记住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

consturl=”http://codeforces.com/api/contest.list?gym=true";
获取(url)
.那么(
response=>response.json()/.text()等。
//与函数(response){return response.json();}相同
).那么(
jsonString=>{
const json=json.parse(jsonString);
document.getElementById(“id01”).innerHTML=json[1].id;
}
);