API Forismatic JSON:随机报价机

时间:2016-08-29 02:23:33

标签: javascript html json

我目前正在使用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 它不会生成报价。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

我认为这是跨源资源共享(CORS)问题,您通过https访问codepen.io,但forismatic API仅通过http afaik提供。 您可以尝试http://codepen.io并查看它是否有效。在尝试通过https使用API​​时,我自己遇到了同样的问题。