如何正确调用javascript回调函数
我不熟悉javascript及其回调函数,我得到了这个超级简单的脚本,我在其中创建了一个函数,我使用jQuery.getJSON检索一些JSON数据,然后返回目标值,当我运行这个脚本时,我无法获得预期的输出,我应该如何调用javascript回调函数如何正确调用javascript回调函数,javascript,jquery,Javascript,Jquery,我不熟悉javascript及其回调函数,我得到了这个超级简单的脚本,我在其中创建了一个函数,我使用jQuery.getJSON检索一些JSON数据,然后返回目标值,当我运行这个脚本时,我无法获得预期的输出,我应该如何调用javascript回调函数 <!DOCTYPE html> <html> <head> <meta http-equiv='X-UA-Compatible' content='IE=edge' /> <ti
<!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>
var parseSheet=函数(url){
var输出=”;
$.getJSON(url、函数(数据){
输出=data.version;
console.log(output);//这将在回调后调用
});
返回输出;
};
变量输出=parseSheet(“https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json");
console.log(输出);//这将首先调用并注销空字符串。
要将其更改为回调:
<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>
var parseSheet=函数(url,回调){
var输出=”;
$.getJSON(url、函数(数据){
输出=data.version;
回调(输出);//这将在回调之后调用
});
};
var输出;
解析表(“https://spreadsheets.google.com/feeds/cells/1sufzdGG7olnxg1P_cEmlwuVsbo1W65grcpzshgVrNoQ/od6/public/values?alt=json“,函数(输出){
输出=输出;
});