以下代码应显示随机引用。但它什么也没有回来。只显示html页面布局。为什么跟随javascript回调函数不起作用:
$(document).ready(function() {
function cb() {
var addr = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
$.getJSON(addr, function(rslt) {
return rslt;
});
};
function qte(rslt) {
$("#qti").html(rslt[0].content);
$("#athr").html(rslt[0].title);
};
qte(cb);
$("#nqt").on("click", function() {
qte(cb);
});
$("#tit").on("click", function() {
window.open("https://twitter.com/intent/tweet?text=" + encodeURIComponent(qwe));
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<h1 class="text-center" style="margin-top:20px;">Random Quote Generator</h1>
<div class="box">
<div class="qt">
<span id="qti"></span>
</div>
<div class="athr">- <span id="athr"></span></div>
<div style="width:100%; clear:both; margin-left:auto; margin-right:auto; margin-top:6%;">
<button class="btn" title="twitt it!" id="tit"><i class="fa fa-twitter"></i></button>
<button class="btn pull-right" id="nqt">New Quote</button>
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
你可以这样做。一旦异步调用可以获得响应,请使用$.when触发qte
函数。
$(document).ready(function() {
function cb() {
// changed http to https to avoid blockrd content
var addr = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
// returning the 'promise' from this function
return $.getJSON(addr, function(rslt) {
return rslt;
});
};
// when cb function has finished execution using its result to populate the fields
$.when(cb()).done(function(rslt){
$("#qti").html(rslt[0].content);
$("#athr").html(rslt[0].title);
});
// rst of code
});