2017-05-06 49 views
-1

下面的代碼應該顯示一個隨機引用。但它什麼都沒有返回。只顯示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

回答

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 
}); 

DEMO

+0

Tnx。但它沒有奏效。當我使用警報時,它說未定義。這意味着它從JSON通話中什麼也沒有得到。但是當我在瀏覽器窗口中訪問該網址時,它給了我一個數組,這意味着url工作正常。 –

相關問題