挣扎着用Javascript来理解AJAX

时间:2018-05-27 20:50:17

标签: javascript ajax github

我是编程新手。

我正在尝试将{我的两个空的)GitHub存储库列表输出到<p> id="repos"。当我运行代码时,收到错误消息:

  

未捕获的ReferenceError:在XMLHttpRequest.gitHubRequest.onreadystatechange

中未定义id

对于我想从(full_name&amp; html_url)中提取值的其他两个键,我将收到此错误。

有人可以告诉我如何使这段代码有效吗?它需要是Javascript-它是一个类。谢谢你!

&#13;
&#13;
let gitHubRequest = new XMLHttpRequest();
gitHubRequest.open('GET', 'https://api.github.com/users/billythesailor/repos', true);

gitHubRequest.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        var repos = JSON.parse(this.responseText);

        var output = '';
        for(var i in repos){
            output +=
            '<ul>' +
            '<li>ID: ' +id[i]+'</li>' +
            '<li>Full Name: ' +full_name[i]+'</li>' +
            '<li>URL: ' +html_url[i]+'</li>'+
            '</ul>'
        }

        document.getElementById('repos').innerHTML = output;
    }
}

gitHubRequest.send();
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

问题是,idfull_namehtml_url是repo对象上的字段,但您可以按定义的数组访问它们。因此id[i]需要更改为repos[i].id,依此类推。我已在下面更新了您的示例!

&#13;
&#13;
let gitHubRequest = new XMLHttpRequest();
gitHubRequest.open('GET', 'https://api.github.com/users/billythesailor/repos', true);

gitHubRequest.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        var repos = JSON.parse(this.responseText);
        var output = '';
        for(var i in repos){
            output +=
            '<ul>' +
            '<li>ID: ' + repos[i].id +'</li>' +
            '<li>Full Name: ' + repos[i].full_name +'</li>' +
            '<li>URL: ' + repos[i].html_url +'</li>'+
            '</ul>'
        }

        document.getElementById('repos').innerHTML = output;
    }
}

gitHubRequest.send();
&#13;
<div id="repos"></div>
&#13;
&#13;
&#13;

此外,如果您是Javascript的新手,并且有兴趣发出ajax请求,请查看Fetch API,这样可以使用它更清晰。

fetch('https://api.github.com/users/billythesailor/repos')
  .then(res => res.json())
  .then(repos => {
    // do stuff with the repo data!
  });