2017-06-21 53 views
0

我有一個jQuery腳本從api拉動報價,數據以json格式返回。然後我試圖在頁面上顯示輸出。但由於某種原因,我無法從api獲取數據。我在這裏做錯了什麼? 感謝爲什麼這jQuery沒有顯示JSON響應

<html> 
<head> 
<title>Qoute Machine</title> 
    <script> 
    $(document).ready(function() { 
    $("#getMessage").on("click", function(){ 
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) { 
    $("#quote").html(JSON.stringify(a.content + " " + a.title)); 
}); 
}); 
    </script> 
</head> 
<body> 
<h1>Welcome to Random Quotes!</h1> 
<p>Press the button to display a quote!.</p> 
    <button id="getMessage" type="button" onclick="getQuote();">Get quote</button> 
    <p id="quote"></p> 

</body> 
</html> 
+0

控制檯中有任何錯誤? –

+0

當你調試這個時,'a'是否包含你期望的內容?它包含什麼? – David

+0

這個頁面是否在內部(quotesondesign.com)? – MahdiY

回答

0

a已經被解析爲JSON,所以你不需要它字符串化輸出的a兩個屬性用空格隔開。事實上,這甚至不是有效的JSON。

您試圖對非JSON進行字符串化。只需使用:

$("#quote").html(a.content + " " + a.title); 

但是,請在片段下面的註解,有一個跨域問題與要求:

$("#getMessage").on("click", function() { 
 
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) { 
 
     $("#quote").html(a.content + " " + a.title); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1>Welcome to Random Quotes!</h1> 
 
<p>Press the button to display a quote!.</p> 
 
<button id="getMessage" type="button">Get quote</button> 
 
<p id="quote"></p>

+0

你是什麼意思交叉來源?... – miatech

+0

這是應該用ajax或JSON API在jQuery中完成?謝謝 – miatech

0

它缺少});在程序結束你不需要JSON.stringify,因爲getJSON返回json或javascript對象,你也不需要onclick="getQuote();",因爲它已經由jQuery處理了$("#getMessage").on("click"。如果從不同的域訪問的最後一個,那麼你需要啓用跨域(CORS)

演示,讓CORS:https://jsfiddle.net/ng5ut2L5/1/

下面

,計算器是不是不允許CORS

$(document).ready(function() { 
 
    $("#getMessage").on("click", function() { 
 
    $.getJSON("//quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) { 
 
     $("#quote").html(a[0].content + " " + a[0].title); 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<h1>Welcome to Random Quotes!</h1> 
 
<p>Press the button to display a quote!.</p> 
 
<button id="getMessage" type="button">Get quote</button> 
 
<p id="quote"></p>

+0

順便代碼不運行jsfiddle – miatech

+0

什麼瀏覽器?你可以查看它的行動https://i.stack.imgur.com/CKzg1.gif – uingtea

+0

你是如何得到它的?我正在玩這個代碼,不能得到這個東西。這並不困難。 – miatech