Making a simple API call using jQuery getJSON

I am trying to create a simple random code generator in a code reader, as you can see here: http://codepen.io/scabbyjoe/pen/dXQmLw

Relevant code inserted below:

<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));
        });
    });
});

I am afraid that I should misunderstand the getJSON tool, since I cannot load content into my div .quote.

Can someone explain why this is not working?


I am trying to follow from this (separate) example, which really works:

<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>
+4
source share
2 answers

Check your console for errors:

XMLHttpRequest http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. "Access-Control-Allow-Origin". Origin 'http://s.codepen.io', , .

AJAX , , . , .

, ; . , . . , - API .

+6

:

XMLHttpRequest http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. "Access-Control-Allow-Origin" . http://s.codepen.io ' .

, api.forismatic.com .

jquery.ajax crossDomain option


+2

Source: https://habr.com/ru/post/1650607/


All Articles