responseJson - 放入函数内部时无法访问

responseJson - Cannot access when put inside of function

在我的 javascript 文件中,我已经在我的 JS 文件的第 19、30 和 35 行指出了我的问题所在。我可以让 responseJson 在 getUserRepos() 函数中登录到控制台,但是如果我尝试在 displayResults() 函数内将它登录到控制台,我会收到错误消息。一旦我可以访问它,我就可以遍历它并检索完成此作业所需的信息。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="main.css">
    <title>GitHub User API</title>
</head>

<body>

    <header>
        <h1>Search for GitHub User Repos</h1>
    </header>

    <form>
        <label for="input"></label>
        <input type="text" id="input" class="input" name="input" value="DusVen44">
        <input type="submit" value="Search">
    </form>

    <p class="error-message"></p>

    <section id="results" class="hidden">
        <h2>Search Results</h2>
        <ul class="results-list">

        </ul>
    </section>


<script src="https://code.jquery.com/jquery-3.5.0.js" 
        integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" 
        crossorigin="anonymous"></script>    
<script src="index.js"></script>
</body>
</html>



* {
    box-sizing: border-box;
}

.hidden {
    display: none;
}

ul {
    list-style-type: none;
}



console.log("hey")

let searchInput = $("#input").val();
console.log(searchInput)

let baseURL = "https://api.github.com/users/" + searchInput + "/repos";
console.log(baseURL)



function getUserRepos() {
    fetch(baseURL) 
        .then(response => {
            if (response.ok) {
                return response.json();
            } throw new Error(response.statusText);
        })
        .then(responseJson => console.log(responseJson))
        .then(responseJson => displayResults())//Here is where I'm calling the function
        .catch(error => alert("Something went wrong"));
    }

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

//This function works until I try to access responseJson
function displayResults() {
    console.log("Hey");
    $(".results-list").empty();
    $(".results-list").append(`<h1>This is a test</h1>`);
    console.log(responseJson);//This causes an error
    // responseJson.each(function(data) {
    //     console.log(data);
    // });
        // $(".results-list").append(
        //     `<li><h2>${responseJson[i].name}</h2>
        //      <h2><a href="${responseJson[i].html_url}</h2>
        //      </li>`
        // )
    // };
    $("#results").removeClass("hidden");
}


// getUserRepos()
submitForm()

当您调用 displayResults 时,您没有将 responseJson 作为参数传递。这是这里唯一的问题,因为 responseJson 没有在 displayResults 函数中定义。

这是因为你没有将 responseJson 传递给函数。 responseJson 仅在 .then 范围内可用。 最简单的方法是做

.then(responseJson => displayResults(responseJson))

function displayResults(responseJson ) { //your code //console.log(responseJson); }

//编辑

.then(responseJson => displayResults(responseJson))

可以缩短为

.then(displayResults)

因为不需要创建箭头函数将responseJson传递给其他函数,直接调用即可。