Akshay Jr. Akshay Jr. - 4 months ago 8
Javascript Question

How to display JSON content using Jquery

JSON.stringify()
displays content in
JSON
format.I would like the quote in
quote
class and character in
character
class.So that on click of button i'll get message and quote displayed.

//HTML

<div class="container-fluid">
<div class = "row text-center">
<h2>GOT Quotes</h2>
</div>
<div class = "row text-center">
<div class = "col-xs-12 well quote">
The message will go here
<br>
<div class = "col-xs-12 well character">
Said By
</div>
</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>

//JS

<script>$(document).ready(function () {
$('#getMessage').click(function () {
$.getJSON('https://got-quotes.herokuapp.com/quotes', function (json) {
$('.quote').html(JSON.stringify(json));
});
});
});

Answer

Is this what you want? Note that I moved the quote class down to a span within the div so you don't overwrite the nested character div. I also used .text() instead of .html(). This is the right thing to do if you're dealing with text.

$(document).ready(function () {
    $('#getMessage').click(function () {
        $.getJSON('https://got-quotes.herokuapp.com/quotes', function (data) {
            $('.quote').text(data.quote);
            $('.character').text(data.character);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class = "row text-center">
    <h2>GOT Quotes</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well">
      <span class="quote">The message will go here</span>
      <br>
      <div class = "col-xs-12 well character">
        Said By
      </div>
    </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>

Comments