0

我正在为使用 Github API 的学校作业构建应用程序。您搜索一个用户,它应该以列表形式返回他们的 Github 存储库,并带有指向其存储库的链接。我已将代码缩减为在控制台中显示 JSON,但在将其附加到我的页面以显示结果的函数中无法识别它。

编辑:将“响应”作为参数传递给函数 displayResults() 似乎已经解决了第一个问题。

下一个问题:我现在在控制台中收到一个 typeError 声明:

未捕获(承诺中)类型错误:无法在 displayResults 处读取未定义的属性“0”

JS:

"use strict";

submitForm();

function submitForm(){
    $('form').submit(function(event){
        event.preventDefault();
        getUserRepos();
    });
};

function getUserRepos(){
    var insertText = $('.inputBox').val();

    fetch(`https://api.github.com/users/${insertText}/repos`)
        .then(response => response.json())
        .then(response => displayResults(response))

};

function displayResults(response){

    $('#results-list').empty();

    for(let i = 0; i < response.length; i++){
        $('#results-list').append(
            `<li>
            <h3><a href="${response.url[i]}"></h3>
            <h3><p>${response.name[i]}</p>
            </li>`
        )
    };

    $('#results').removeClass('hidden');
};

HTML:

<!DOCTYPE html>
<html class="no-js">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>

        </title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container">
            <h1>Search GitHub User Repos</h1>
            <form>
                <label>Search Users</label>
                <input class="inputBox" type="text" required>

                <input type="submit">
            </form>

            <section id="results" class="hidden">
                <h2>Search Results</h2>
                <ul id="results-list">    
                </ul>
            </section>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
        <script src="script.js"></script>
    </body>
</html>
4

1 回答 1

1

在从 API 获取响应之前调用您的函数displayResults 。

尝试使您的功能为

function getUserRepos(){
    var insertText = $('.inputBox').val();
    fetch(`https://api.github.com/users/${insertText}/repos`)
        .then(response => response.json())
        .then(response => { 
            console.log(response)
            displayResults();
        });
};
于 2019-12-29T07:18:19.790 回答