2017-06-21 51 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