繁体   English   中英

为什么我的 JSON 响应无法在另一个函数中识别?

[英]Why is my JSON response not recognized in another function?

我正在为使用 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>

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

尝试使您的功能为

function getUserRepos(){
    var insertText = $('.inputBox').val();
    fetch(`https://api.github.com/users/${insertText}/repos`)
        .then(response => response.json())
        .then(response => { 
            console.log(response)
            displayResults();
        });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM