Professional Documents
Culture Documents
Javascript in A Nutshell: Corso Di Laurea Magistrale in Scienze Di Internet Knowledge Management Andrea Nuzzolese
Javascript in A Nutshell: Corso Di Laurea Magistrale in Scienze Di Internet Knowledge Management Andrea Nuzzolese
Andrea Nuzzolese
http://creativecommons.org/licenses/by-sa/3.0
Outline
• Javascript
• AJAX
• JSON
• jQuery
2
History of JavaScript
3
JavaScript and HTML
4
Base syntax
• JavaScript is case-sensitive
✦ helloWorld != helloworld
• Variables
✦ have no type declaration
✦ var y; is the declaration of a variable y
✦ “+” sum in case of both arguments are numbers and concat in case of one
of them is a string <script type="text/javascript">
var y = “Steve ”;
var x = y + “Jobs” // x = “Steve Jobs”
y = 10;
x = y + 5; // x = 15
</script> 5
Conditional statments: if...else and while
<script type="text/javascript">
var y = 4;
var greaterThanZero;
// if...else statement
if(y > 0){
greaterThanZero = true;
}
else{
greaterThanZero = false;
}
// while statement
while(greaterThanZero){
y -= 1; // syntax sugar for y = y - 1;
if(y == 0){
greaterThanZero = !greaterThanZero;
}
}
</script>
6
Conditional statements: for and switch...case
<script type="text/javascript">
// for statement
for(var i=0; i<10; i++){
alert(“The value of i is: ” + i);
}
else{
greaterThanZero = false;
}
// switch statement
var cellWidth = ... // some integer
var cellHeight;
switch(value){
case 50:
cellHeight = 100;
break; // do not execute other cases
case 100:
cellHeight = 50;
break;
default:
cellHeight = 30;
}
</script>
7
Functions
<html>
<head>
<script type="text/javascript">
function product(n, m)
! {
! res = m * n;
! alert("The result of the product is " + res);
! }
</script>
</head>
8
Classes and Objects
/*
* Create a new instance of the class Person.
* This instance represents me.
*/
var me = new Person(“Andrea Nuzzolese”);
10
Prototypes
11
Using prototype for methods
/*
* Create a new instance of the class Person.
* This instance represents me.
*/
var me = new Person(“Andrea Nuzzolese”);
12
Using prototype for inheritance
function Vehicle(passengers) {
this.speed = 0;
this.passengers = 0;
this.load = function(passengers) {
if(passengers > 0) {
this.passengers += passengers;
}
}
this.load(passengers);
}
function Airplane(passengers) {
this.load(passengers);
this.altitude = 0;
this.takeOff = function() {
this.speed = 100;
this.altitude = 10;
}
}
13
Documen Object Model
FORM
TEXT
SELECT
RADIO OPTIONS
CHECKBOX BUTTON
TEXTAREA RESET
PASSWORD SUBMIT
14
JavaScript DOM objects
15
Description of the principal objects
16
The Document object
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function readText (form) {
var testVar =form.inputbox.value;
alert ("You typed: " + TestVar);}
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
Enter something in the box: <BR/>
<INPUT TYPE="text" NAME="inputbox" VALUE=""/>
<INPUT TYPE="button" NAME="button1" Value="Read"
onClick="readText(this.form)"/>
<INPUT TYPE="button" NAME="button2" Value="Write“
onClick="writeText(this.form)"/>
</FORM>
</BODY>
</HTML>
18
Selectors
19
Example
…
<SCRIPT LANGUAGE="JavaScript">
var mainContentEl = document.getElementById("mainContent");
var recommendations =
document.getElementsByClassName("recommendation");
var advertisements =
document.getElementsByName("advertisement");
var documentDivs =
document.getElementsByTagName("div");
</SCRIPT>
</HEAD>
<BODY>
<DIV id="mainContent"> some content </DIV>
<DIV class="recommendation"> recommendation 1 </DIV>
<DIV class="recommendation"> recommendation 2 </DIV>
<DIV id="footnote_left" name="advertisement"> ... </DIV>
<DIV id="footnote_right" name="advertisement">
...
</DIV>
...
20
Ajax
21
Ajax architecture
22
Client-server activities without Ajax
23
Client-server activities with Ajax
24
Ajax interactions
25
Creation of the Ajax object
/*
* The initialization of http_request.onreadystatechange
* allows to specify the function that will manage (see slide
* about request management) the response
*/
http_request.onreadystatechange = nameOfTheFunction;
/*
* The http_request.open opens a connection with a server.
*
* The first parameter specifies the type of HTTP request.
* The second parameter specifies the destination address of
* the request.
* The third parameter is a boolean value that specifies if the
* request should be performed asynchronously (true)
* synchronously (false).
*/
http_request.open('GET','http://www.example.org/some.file',true);
27
Request sending
/*
* Request sending with HTTP GET methods.
* With HTTP GET methods the actual parameter of
* http_request.send is null because the values are passed
* to the server through the URL when the connection is opened.
*/
http_request.send(null);
/*
* Request sending with HTTP POST methods.
* With HTTP GET methods the parameters to send
* to the server are passed as a query-string containing
* couples of attribute=value separated by &.
*/
http_request.send(name=value&othername=othervalue&so=on);
http_request.setRequestHeader('Content-Type', 'multipart/form-data');
28
Request management (1)
/*
* In http_request.onreadystatechange we specified the function
* responsible for the request management. This usually works
* checking the HTTP status code returned by the request.
*/
var manageResponse = funtion() {
if (http_request.status == 200) {
! // perfect!
}
else {
! // there was a problem with the request,
! // for example the response may be a 404 (Not Found)
! // or 500 (Internal Server Error) response codes
}
http_request.onreadystatechange = manageResponse;
/*
29
HTTP status codes
✴ ...
30
Reading the response
• If the status code is 200 (OK) the response sent by the server
can be read
31
Example
33
JSON
34
JSON data structures
35
JSON object
36
Example
/*
* This is an example of JSON object.
* It is a collection of comma-separated name:value pairs.
* A value can be a string, a number, a boolean, an
* object (see address), an array, and a null.
*/
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
}
}
37
JSON array
38
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
\\ Here we add an array containing other objects as values
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
} 39
JSON value
40
Hot to manage JSON with JavaScript and Ajax
41
Example
// initialize the XMLHttpRequest object request
myXMLHTTPRequest = new XMLHttpRequest();
43
jQuery’s features
• DOM manipulation based on CSS selectors that uses node elements name and node
elements attributes (id and class) as criteria to build selectors
• Events
• Ajax
• Compatibility methods that are natively available in modern browsers but need
fallbacks for older ones - For example the inArray() and each() functions.
• Cross-browser support
44
Including jQuery
<HTML>
<HEAD>
...
<SCRIPT type="text/javascript" src="jquery.js"></SCRIPT>
..
</HEAD>
<BODY>
...
</BODY>
</HTML>
45
jQuery Vs. JavaScript
$(“div”).hide();
46
jQuery selectors
47
Attributes (1)
• .addClass()
✦ Manages Class Attribute, CSS
✦ Adds the specified class(es) to each of the set of matched elements.
• .attr()
✦ Manages general attributes
✦ Get or set the value of an attribute for the first element in the set of
matched elements.
• .hasClass()
✦ Manages Class Attribute, CSS
✦ Determine whether any of the matched elements are assigned the given
class.
• .html()
✦ Manages DOM Insertion, Inside
✦ Get or set the HTML content of48 the first element in the set of matched
Attributes (2)
• .prop()
✦ Manages general attributes
✦ Get or set the value of a property for the first element in the set of
matched elements.
• .removeAttr()
✦ Manages general attributes
✦ Remove an attribute from each element in the set of matched elements.
• .removeClass()
✦ Manages class attributes and CSS
✦ Remove a single class, multiple classes, or all classes from each element in
the set of matched elements.
• .removeProp()
✦ Manages general attributes
✦ Remove a property for the set of
49 matched elements.
Attribute (3)
• .toggleClass()
✦ Manages Class Attribute, CSS
✦ Add or remove one or more classes from each element in the set of
matched elements, depending on either the class's presence or the value of
the switch argument.
• .val()
✦ Manages forms and general attributes
✦ Get or set the current value of the first element in the set of matched
elements
50
Example
/*
* add the class enabled_contact to the element with ID contact5
*/
$(“#contact5”).addClass(“enabled_ contact”);
/*
* remove the class disabled_contact to the element with ID contact5
*/
$(“#contact5”).removeClass(“disabled_ contact”);
/*
* copy the html content from the first element in the list
* to the element with ID contact5
*/
$(“#contact5”).html($(“li:first”).html());
/*
* add solid red border with a 3px line to the elements
* of the class frame
*/
$(".frame").css("border","3px solid red");
51