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