Javascript变量范围:从回调函数中提取变量[重复]

时间:2022-02-28 09:56:56

This question already has an answer here:

这个问题在这里已有答案:

this is some basic variable scope question, but I can't figure how to "extract" a variable from a async callback function:

这是一些基本的变量范围问题,但我无法想象如何从异步回调函数中“提取”变量:

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <div id="container"></div>
    <script>

    var API_KEY = "***";
    var USERNAME = "***";
    var res;

        $(
            start()
        );

        function start(){

            $.getJSON(
                "https://www.googleapis.com/youtube/v3/channels",
                {"part": "contentDetails", "forUsername": USERNAME, "key": API_KEY},
                function(data){
                    alert("Success");

                    var s = "";
                    s = data.items[0].contentDetails.relatedPlaylists.uploads;

                    $("#container").html(s);
                    var res = s;
                }
            );

        };
    </script>
</body>

</html>

I've got this code fetching info about a Youtube channel, and I try to put "s" in "res" that is a global variable, but it doesn't works. Is there some way to do it ?

我有这个代码获取有关Youtube频道的信息,我尝试将“s”放在“res”中,这是一个全局变量,但它不起作用。有办法吗?

(Also if someone knows a better way to extract data from the response object returned by getJSON, it would be a better idea, but I can't figure that out either...)

(如果有人知道从getJSON返回的响应对象中提取数据的更好方法,那将是一个更好的主意,但我无法弄明白......)

Thanks

谢谢

1 个解决方案

#1


-1  

update below code.remove var from res in side success function . read more about javascript variable scope HERE

更新下面的代码。从侧面成功函数中删除res中的res。阅读更多关于javascript变量范围的信息

function start(){

        $.getJSON(
            "https://www.googleapis.com/youtube/v3/channels",
            {"part": "contentDetails", "forUsername": USERNAME, "key": API_KEY},
            function(data){
                alert("Success");

                var s = "";
                s = data.items[0].contentDetails.relatedPlaylists.uploads;

                $("#container").html(s);
                 res = s;
            }
        );

    };

#1


-1  

update below code.remove var from res in side success function . read more about javascript variable scope HERE

更新下面的代码。从侧面成功函数中删除res中的res。阅读更多关于javascript变量范围的信息

function start(){

        $.getJSON(
            "https://www.googleapis.com/youtube/v3/channels",
            {"part": "contentDetails", "forUsername": USERNAME, "key": API_KEY},
            function(data){
                alert("Success");

                var s = "";
                s = data.items[0].contentDetails.relatedPlaylists.uploads;

                $("#container").html(s);
                 res = s;
            }
        );

    };