Today we had our second lab session for Application Frameworks and I found this particular part of the labsheet interesting.
What we have to do is, to create a function that would call the GitHub API. The url
https://api.github.com/users returns a JSON string. So first lets grab it using a simple HTTP request. I created the following class to send a HTTP request.
In it there's a method called get() which take two arguments, the URL and a callback function. Basically, what it does is , it creates a instance of
XMLHttpRequest which we would use to send the request. It supports both synchronous and asynchronous communications. But synchronous communications block the execution of the code and creates negative user experience. Hence asynchronous communications should be preferred.
The
onreadystatechange is an EventHandler that is called when the readyState attribute is changed. The
readyState attribute returns the state in which the XMLHttpRequest client is in. A readyState of 4 denotes that the request is complete and a status of 200 can be either th request is currently loading or is complete. The callback function is used to decide upon what should be done using the response text once it is received.
The
open() method is used to initialize the request. It takes three arguments namely the method of request (GET/POST/PUT/DELETE...etc), the URL and 'async' which decides whether it is synchronous or asynchronous communication to be used which is optional. Here we use asynchronous communication, hence the async is set to true.
The
send() method is used to send the request. If the request is asynchronous, this method would return as soon as the request is sent. But if it is synchronous, it would not return until the response has been received.
Now that we have the class, lets send the request.
First I created an instance from the class HttpClient (The one I created). Then I passed the URL to the get method call plus defined the callback function in which the response data which is JSON string would be manipulated.
Now to the callback function. We know that the response contains a JSON string. But in order to use the data in it, we first need to convert this into a JSON object. To do so, I used the parse method in JSON. Now that we have an array of data waiting for us, we'll display some of the content.
I used a <div> tag to display it. Got reference to the tag using an id and set the innerHTML to show the login and the type of each user record.
Output:
<<Nandun Bandara>>