HTML and CSS Reference
In-Depth Information
It is possible to perform AJAX calls using the inbuilt JavaScript object, however jQuery
provides an AJAX wrapper that provides a more convenient mechanism for performing
AJAX calls.
In order to try out some AJAX examples, we will make our server return static JSON when
a particular URL is requested.
Create a new directory in the directory containing tasks.html called “server”.
Add a file to this called tasks.json, and add the following content:
[{"id":100,"task":"first task","requiredBy":"2013-09-03","category":"Personal"},
{"id":101,"task":"second task","requiredBy":"2013-10-03","category":"Work"},
{"id":102,"task":"third task","requiredBy":"2013-09-05","category":"Work"},
{"id":103,"task":"last task","requiredBy":"2013-09-08","category":"Personal"}]
This JSON contains an array, which in turn contains 4 task objects. Each of these task ob-
jects have the same properties as those created by the web application.
In order to request this using AJAX, first browse to the tasks.html page. AJAX calls can
only be made to the same server name and port as the page that has been loaded in the
browser: this is known as the same-origin policy. There are ways around the same-origin
policy if necessary, but these tend to rely on hacks: JSONP is the most prominent approach
for this if you are interested.
Next open up the console, and type the following:
$.ajax({
type : "GET",
dataType: "json",
url : "/server/tasks.json",
cache : false,
success : function(data) {
console.log(data);
}
});
This request is taking advantage of the jQuery static function $.ajax. Although this is relat-
ively simple, there is quite a lot here that needs explaining:
• The request is an HTTP GET request: this is the default so could have been omitted.
Search WWH ::




Custom Search