How to Invoke APIs – The Javascript/Ajax/JQuery Example


I have provided some Free/Funny APIs for everybody to use subject to a fair use policy. All APIs are implemented and running on this VPS. The list of APIs can be found here.

Take fortune API for example, you can call the API using Javascript/AJax so that the message is displayed on the browser.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type='text/Javascript' src='https://helloacm.com/jquery/jquery-2.1.4.min.js'></script>
<script type='text/Javascript'>
$(document).ready(function () {
  $.ajax(
    {
        dataType: "json",
        url: "https://helloacm.com/api/fortune/", 
        cache: false, 
        success: function (response) {
          document.write(response);
        }
    })        
});                
</script>
<script type='text/Javascript' src='https://helloacm.com/jquery/jquery-2.1.4.min.js'></script>
<script type='text/Javascript'>
$(document).ready(function () {
  $.ajax(
    {
        dataType: "json",
        url: "https://helloacm.com/api/fortune/", 
        cache: false, 
        success: function (response) {
          document.write(response);
        }
    })        
});                
</script>

With little modification, we define a place for string to display in the browser,

<div id='fortune_text'> </div>

and, we change the above document.write to $(‘#fortune_text’).html(response).

We can see the random adage everytime the following if you refresh the page/click the button.




The JQuery library provides handy JSON and Ajax features so that the response from Ajax can be treated as JSON-string directly.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
350 words
Last Post: Common Algorithms and Their Complexity
Next Post: Linux Easter Egg - apt-get moo

The Permanent URL is: How to Invoke APIs – The Javascript/Ajax/JQuery Example

Leave a Reply