从XMLHttprequest获取数据

时间:2015-04-09 08:40:24

标签: 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", 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代码中,我有一个id =&#34; id01&#34;

的div

3 个答案:

答案 0 :(得分:1)

请记住,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;
}
}

答案 1 :(得分:0)

试试这个:

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

获取此代码

答案 2 :(得分:0)

只需使用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