简体   繁体   中英

How to get and display JSON API data with JavaScript

I am a beginner learning web development. I am trying to create a web app based on HTML, CSS, and JavaScript, which:

  1. Receives input from a user through an input field
  2. Retrieves JSON data through an external API
  3. Displays the results below the input field.

After some research, my conclusion was that Node.js, Bootstrap and Heroku would be a good setup to do this. However, I am currently stuck when it comes to calling and displaying the data from API.

In the API instructions, the following code is supplied as "jQuery demo":

$.ajax({
  'url': 'http://apis.is/car',
  'type': 'GET',
  'dataType': 'json',
  'data': {'number': 'aa031'},
  'success': function(response) {
    console.log(response);
  }
});

I used this to create the following .js file, which I reference at the bottom of my html body contents, alongside jQuery:

$( document ).ready(function() {
    $.ajax({
        'url': 'http://apis.is/car',
        'type': 'GET',
        'dataType': 'json',
        'data': {'number': 'aa031'},
        'success': function(response) {
          console.log(response);
        }
    });
});

Everything seems to run correctly, but I am a bit lost when it comes to finding out what to do next to make this work:

  1. How can I take the user input from the field and put it in the API query?
  2. How do I insert the results from the query into the table?

Thank you in advance for any help!

You've got two parts here - how do I customize the request being sent to the api, using information that someone entered into your page, and then how do you display that data once it comes back.

For the first part, you're really close. You'll need an input field to take in the number you want to send. You can see in the comments of the snippet how this is laid out. You don't have to use a button to submit it, but that's just the way I did it here.

 // this function will accept inputText as an argument, which you can then use inside your ajax call, like you see below right next to 'number' function getAPIData(inputText) { $.ajax({ 'url': 'https://apis.is/car', 'type': 'GET', 'dataType': 'json', 'data': {'number': inputText}, 'success': function(response) { console.log(response); }, 'error': function(response) { console.log(response.statusText); } }); }; $("#check-api").click(function() { // our inputText is going to be equal to the value of the input field var inputText = $("#api-input-field").val(); // then, as long as our input field isn't blank, let's call that function above and pass in the inputText as an argument if (inputText !== "") { getAPIData(inputText); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h5>Type in a number here and click the button to see a console log message appear.</h5> <input id="api-input-field" type="text"> <button id="check-api">Check API</button> 

For the second part, have you tried anything yet with JSON data? Do you know how to iterate over things, in javascript? I'm absolutely happy to help you there, too, but I think it's good to try a few things first on your own first just to see how far you can get. Do you have any examples of ways you've gone about it so far?

 $(document).ready(function() { function request(s){ $.ajax({ 'url': '//apis.is/car', 'type': 'GET', 'dataType': 'json', 'data': { 'number': s }, 'success': function(response) { // console.log(response); if (response && response.results && response.results.length) { response.results.forEach((car) => { Object.keys(car).forEach((key) => { $('<div>').html(`${key} : ${car[key]}`).appendTo($('body')); }); }); } } }) } $('#search').click(() => { request($('#val').val()); }); }); 
 <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <input id="val" placeholder="Type here" type="text"> <button id="search">Search</button> </body> </html> 

  1. How can I take the user input from the field and put it in the API query?

As you are using jQuery, try $("#input_id").val() , where the # selector means you're looking for the id of the input and the input_id is the actually id of the input. After that, the function val() get it's val.

If you want, you can even use the class of the input using . instead of # . I recommend you to get more information here .

You can save it on a var, doing var value = $("#input_id").val()

As you already had the ajax, just change:

$( document ).ready(function() {
$.ajax({
    'url': 'http://apis.is/car',
    'type': 'GET',
    'dataType': 'json',
    'data': {'number': 'aa031'},
    'success': function(response) {
      console.log(response);
    }
})});

for

$( document ).ready(function() {
$.ajax({
    'url': 'http://apis.is/car',
    'type': 'GET',
    'dataType': 'json',
    'data': {'number': value},
    'success': function(response) {
      console.log(response);
    }
})});

How do I insert the results from the query into the table?

Where you are doing the console.log(response); you can use the .append api from jQuery, like: $( "inner" ).append("<p>response.results[0].type</p>"); This will append a paragraph with the type of the car received from your api. Keep in mind the response is an object and you can access it's property just like any other object. See this for more information about append.

I will finish it with one advice: As you are starting now and using node, try some javascript framework, such as React or Vue.js and enjoy the power of ES6. For beginning, Vue.js is simplier. This thing will change your life. Good luck in your development! ;)

See the snippet below, hope it helps:

$(document).ready(function() {
    $('.form-group input').keypress(function(e) {
        if (e.which === 13) { //search triggers when Enter key is pressed in the textbox
            $.ajax({
                'url': 'http://apis.is/car',
                'type': 'GET',
                'dataType': 'json',
                'data': { 'number': $('.form-group input').val() },
                'success': function(response) {
                    if (response.results) {
                        var html = '';
                        for (var i = 0; i < response.results.length; i++) {
                            html += '<table><thead class="thead-default"> <tr> <th>Reitur</th> <th>Gildi</th> </tr> </thead>';
                            html += '<tr><td>Tegund</td><td>' + response.results[i].type + '</td></tr>';
                            html += '<tr><td>Undirgerð</td><td>' + response.results[i].subType + '</td></tr>';
                            html += '<tr><td>Litur</td><td>' + response.results[i].color + '</td></tr>';
                            html += '<tr><td>Verksmiðjunúmer</td><td>' + response.results[i].factoryNumber + '</td></tr>';
                            html += '<tr><td>Skráður</td><td>' + response.results[i].registeredAt + '</td></tr>';
                            html += '<tr><td>Mengun</td><td>' + response.results[i].pollution + '</td></tr>';
                            html += '<tr><td>Þyngd</td><td>' + response.results[i].weight + '</td></tr>';
                            html += '<tr><td>Skoðunarstaða</td><td>' + response.results[i].status + '</td></tr>';
                            html += '<tr><td>Næsta skoðun</td><td>' + response.results[i].nextCheck + '</td></tr>';
                            html += '</table><p>&nbsp</p>';
                        }
                        $('#results').html(html);

                    }
                }
            });
        }
    });
});

Make sure you have jQuery JS added to your page before the position where the above script in included:

   <script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

Try this as a basic flow. Create an input field, id of search and give it an event listener. Looks like you're using jQuery, so you could do something like this in your javascript.

$("#search").keydown(e => { 
  if (e.which === 13) {
    callApi($("#search").val()) 
  }
})

When you hit enter, this will take whatever value is in your input box and pass it as a value to your callAPI() function. Create a callAPI(value) function that accepts that value and does your ajax call with the value. And then on success - append your results to your html element of choice.

The above flow would work perfectly fine if you wanted to create a button and submit the request on click of that button as well, very similar approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM