回调函数在下面的代码中不起作用?

问题描述:

下面的代码应该显示一个随机引用。但它什么都没有返回。只显示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>

+4

的回调的getJSON是异步调用的,所以你的回调是没有做任何事情。 – jdigital

+0

你知道你的cb函数没有返回任何东西吗? –

+1

你的浏览器有一个内置的调试器。对于深入了解这类问题非常有帮助。我建议花时间学习使用它。 – jdigital

你可以这样做。一旦从异步调用获得响应,使用$.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 
}); 

DEMO

+0

Tnx。但它没有奏效。当我使用警报时,它说未定义。这意味着它从JSON通话中什么也没有得到。但是当我在浏览器窗口中访问该网址时,它给了我一个数组,这意味着url工作正常。 –