JQuery is a popular lightweight, "write less, do more", JavaScript library while Aurelia is a modern, open source client side JavaScript framework for web and mobile application development. In this article, we will look into how to use JQuery with Aurelia for a GET Request.
Introduction
JQuery is a popular lightweight, "write less, do more", JavaScript library while Aurelia is a modern, open source client side JavaScript framework for web and mobile application development. In this article, we will look into how to use JQuery with Aurelia for a GET Request.
Aurelia - Project Setup
Create a folder say AureliaExperiment at your favorite location.
Then download the basic Aurelia project setup zipped file from here.
Extract the Zipped file and copy it under AureliaExperiment folder. It looks as under
Straight to Experiment
At first, we need to install JQuery from here.
As a second step, we need to add
import $ from 'jquery';
in the
app.js file. We can then use the
$ JQuery symbol for the JQuery operation. Let us look into our implementation for
app.js file.
app.js
---------
import $ from 'jquery';
export class App {
constructor() {
this.UserRecords = this.fetchUserDataFromWebService();
}
fetchUserDataFromWebService()
{
var serverData = "";
$.ajax({
type: "get",
url: "http://jsonplaceholder.typicode.com/posts",
cache: false,
data: {},
async: false,
success: function (data) {
serverData = data;
},
error: function (err) {
alert(err);
}
});
return serverData;
}
}
The program is very simple.The ajax() method is used to perform an AJAX (asynchronous HTTP) request and capturing the server response in the serverData variable. We have captured the GET Request result in the UserRecords property inside the Constructor of the App class.
Now let's open the app.html file and write the below template
app.html
---------
<template>
<table border="1">
<thead>
<tr>
<td><b>Id</b></td>
<td><b>UserId</b></td>
<td><b>Title</b></td>
<td><b>Description</b></td>
</tr>
</thead>
<tbody>
<tr repeat.for="userRecord of UserRecords">
<td>${userRecord.id}</td>
<td>${userRecord.userId}</td>
<td>${userRecord.title}</td>
<td>${userRecord.body}</td>
</tr>
</tbody>
</table>
</template>
The purpose of Repeat.for is to iterate over objects. After we iterate the UserRecords array, we have bound the properties of the object by using the {object.property} syntax of Aurelia. The result is as under
We can use the JavaScript slice() method for limiting the array size. THe general syntax is
array.slice(start,end)
In our case the change will be
this.fetchUserDataFromWebService().slice(0,5)
as we are limiting to 5 records. The output
Reference
Benefits of Aurelia
Conclusion
In this article we have learnt how to use JQuery with Aurelia for a GET Request. Hope this will be useful. Thanks for reading. Zipped file attached.