使用 jQuery getJSON 进行简单的 API 调用

Making a simple API call with jQuery getJSON

我正在尝试在 Codepen 中构建一个简单的随机报价生成器,您可以在此处看到:http://codepen.io/scabbyjoe/pen/dXQmLw

下面粘贴相关代码:

<html>
    <head>
    </head>
    <body>
        <h1>Random Quote Machine</h1>
        <div class="quote">
        </div>
        <div class="btn">New Quote</div>
    </body>
</html>

$(document).ready(function() {
    $(".btn").on("click", function(){
        $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
            $(".quote").html(JSON.stringify(json));
        });
    });
});

恐怕我一定是误解了 getJSON 工具,因为我无法在 .quote div.

中加载任何内容

谁能解释为什么这不起作用?


我尝试从这个(单独的)示例中学习,它确实有效:

<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function(){
      $.getJSON("/json/cats.json", function(json) {
        $(".message").html(JSON.stringify(json));
      });

    });

  });
</script>

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>

检查您的控制台是否有错误:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

除非他们明确允许,否则您不能向托管在与您自己的域不同的域上的服务发出AJAX请求。此消息表示不允许。

也许在某些情况下是允许的;检查他们的文档。如果不是,则您必须通过自己的服务器代理 请求。也不能保证在那种情况下是允许的。您可能需要向他们提供 API 密钥之类的东西,或者被添加到白名单中。

您可以在控制台面板中发现错误消息:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

您应该确保 api.forismatic.com 提供允许跨域的资源。

或者您可以查看 jquery.ajax crossDomain 选项