skip to Main Content

I’m trying to get JSON file with ajax and display it in an HTML div but only part of it, not everything.

Here is the ajax

    $(function () {
  $.ajax({
  'url': 'http://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
  'type': 'GET',
  'dataType': 'json',
  'success': function(response) {
  }
});
});

and I’m trying to put just some object for example just the temperature in the HTML div

    <!DOCTYPE html>
<html lang="is" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="js/main.js"></script>
  </head>
  <body>
    <div id="result">
      <p>i want the result here</p>
    </div>
  </body>
</html>

anybody that knows this stuff?

2

Answers


  1. You can start from here, I displayed the whole object but you need to parse the data according to your needs

    $(function() {
      $.ajax({
        'url': 'http://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
        'type': 'GET',
        'dataType': 'json',
        'success': function(response) {
          displayData(response);
        }
      });
    });
    
    function displayData(data) {
      document.getElementById("result").innerHTML  = JSON.stringify(data, null, 4);
      //parse the data and display only the fields that you need and display with innerHTML
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <body>
      <div>
        <p id="result">i want the result here</p>
      </div>
    </body>
    Login or Signup to reply.
  2. Consider the following code.

    $(function() {
      function showHtmlData(obj) {
        var html = "";
        $.each(obj, function(key, value) {
          html += key + ": " + value + "<br />";
        });
        return html;
      }
    
      function showJson(json) {
        $("#result p").html(showHtmlData(json));
      }
      $.ajax({
        'url': 'https://apis.is/weather/observations/en?stations=3696&time=1h&anytime=0',
        'type': 'GET',
        'dataType': 'json',
        'success': function(response) {
          showJson(response.results[0]);
        }
      });
    });
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    
    <div id="result">
      <p></p>
    </div>

    This takes the JSON Data, converts it into a String, and adds it to the <p>.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search