我目前正在使用 forismatic API 构建报价机,但完全被难住了。在我决定将来重新审视我的工作之前,我的程序运行良好。这是我的代码:
var html = "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?";
var getQuote=function(data){
if(data.quoteAuthor === "") {
data.quoteAuthor = "Unknown";
}
$('#author').text(data.quoteAuthor);
$('#text').text(data.quoteText);
var quote = 'https://twitter.com/intent/tweet?text=' + "\"" + data.quoteText + "\"" + ' Author: ' + data.quoteAuthor +' @Gil_Skates';
$('#tweet').attr("href", quote);
};
$(document).ready(function() {
$.getJSON(html, getQuote, 'jsonp');
});
// On button click
$('#new-quote').on("click", function(){
// Deletes text and creates spinner
$('#text').text("");
$('#author').text("");
$('<span style = "margin-left:200px" class="fa-li fa fa-spinner fa-spin"/>').appendTo('#text');
// Calls our random quote
$.getJSON(html, getQuote, 'jsonp');
});
// Tweet popup
window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class = "quote-box centered">
<div class = "quote-text">
<i class="fa fa-quote-left"></i><span id = "text" >Quotes inspire<span>
</div>
<div class = "quote-author">
<span id = "author">Programmer</span>
</div>
<div class = "buttons">
<a class="button" href="https://twitter.com/intent/tweet" data-size="large" id="tweet" title="Tweet this now!" target="_blank">
<i class = "fa fa-twitter"></i>
</a>
<!--<a class="button" id="tumblr" title="Share on Tumblr!" target="_blank">
<i class = "fa fa-tumblr"></i>
</a>-->
<button class = "button" id ="new-quote">New Quote</button>
</div>
</div>
我做错了什么?我创建了一个变量来保存我的 url,创建了一个获取数据的函数,并使用 getJSON 来利用我的函数。 (请原谅我的术语)
当我在这个网站上运行它时它工作,但是在:https://codepen.io/gilioo/pen/JKpjgr 它不会生成报价。
感谢任何帮助。
最佳答案
我认为这是一个跨源资源共享 (CORS) 问题,您正在通过 https 访问 codepen.io,但 forismatic API 仅通过 http afaik 提供。 你可以试试 http://codepen.io看看它是否有效。我在尝试通过 https 使用 API 时遇到了同样的问题。
关于javascript - API Forismatic JSON : Random Quote Machine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197725/