如何正确调用javascript回调函数

时间:2015-05-15 05:24:02

标签: javascript jquery

我是javascript及其回调函数的新手,我得到了这个超级简单的脚本,我创建了一个函数,在其中,我使用jQuery.getJSON来检索一些JSON数据,然后返回目标值,当我运行此脚本,我无法获得预期的输出,我应该如何调用javascript回调函数?

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='X-UA-Compatible' content='IE=edge' />
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <script defer="true">
    var parseSheet = function(url) {
        var output = "";
        $.getJSON(url, function(data) {
            output = data.version;
            console.log(output); // this will called after, callback
        });
        return output;
    };
    var output = parseSheet("https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json");
    console.log(output); // this will called first and log out empty string.
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

将其更改为回调:

    <script defer="true">
    var parseSheet = function(url, callback) {
        var output = "";
        $.getJSON(url, function(data) {
            output = data.version;
            callback(output); // this will called after, callback
        });
    };
    var output;  
    parseSheet("https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json", function(out){
       output = out;
    });
    </script>