Você está na página 1de 33

Resources

http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/JavaScript_basics
http://www.learn-js.org/
http://www.tutorialspoint.com/javascript/
http://www.w3schools.com/ajax/
https://api.jquery.com/
http://www.w3schools.com/jquery/

JavaScript
1. What is JavaScript
JavaScript is a dynamic programming language, most commonly used as part of web browsers,
whose implementations allow client-side scripts to interact with the user, control the browser,
communicate asynchronously, and alter the document content that is displayed. It is also used
in server-side network programming with runtime environments such as Node.js, game
development and the creation of desktop and mobile applications. With the rise of the singlepage web app and JavaScript-heavy sites, it is increasingly being used as a compile target for
source-to-source compilers from both dynamic languages and static languages.
JavaScript is classified as a prototype-based scripting language with dynamic typing and firstclass functions. This mix of features makes it a multi-paradigm language, supporting objectoriented, imperative, and functional programming styles. Despite some naming, syntactic, and
standard library similarities, JavaScript and Java are otherwise unrelated and have very
different semantics. The syntax of JavaScript is actually derived from C, while the semantics
and design are influenced by the Self and Scheme programming languages.

Advantages of JavaScript
The merits of using JavaScript are:
Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations with JavaScript


We can not treat JavaScript as a full fledged programming language. It lacks the following
important features:
Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.

JavaScript can not be used for Networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocess capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.

2.

JavaScript where to

JavaScript can be placed in the <head> and the <body> sections of an HTML page. In HTML,
JavaScript code must be inserted between <script> and </script> tags.
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
JavaScript in <head> - Try it yourself
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript in <body> - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {

document.getElementById("demo").innerHTML = "Paragraph changed.";


}
</script>
</body>
</html>
External JavaScript
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

3.

JavaScript output

JavaScript does not have any built-in print or display functions. JavaScript can "display" data in
different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().
Using window.alert() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);

</script>
</body>
</html>
Using innerHTML - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using console.log() - Try it yourself
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

4.

JavaScript variables and data types

JavaScript variables are containers for storing data values. JavaScript variables can hold many
data types: numbers, strings, arrays, objects and more:
var
var
var
var

length = 16;
lastName = "Johnson";
cars = ["Saab", "Volvo", "BMW"];
x = {firstName:"John", lastName:"Doe"};

//
//
//
//

Number
String
Array
Object

In programming, data types is an important concept. To be able to operate on variables, it is


important to know something about the type.

JavaScript has dynamic types. This means that the same variable can be used as different
types:
var x;
var x = 5;
var x = "John";

// Now x is undefined
// Now x is a Number
// Now x is a String

JavaScript strings
A string (or a text string) is a series of characters like "John Doe". Strings are written with
quotes. You can use single or double quotes:
var carName = "Volvo XC60";
var carName = 'Volvo XC60';

// Using double quotes


// Using single quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double
quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single
quotes
More about strings
JavaScript numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
var x1 = 34.00;
var x2 = 34;

// Written with decimals


// Written without decimals

Extra large or extra small numbers can be written with scientific (exponential) notation:
var y = 123e5;
var z = 123e-5;

// 12300000
// 0.00123

More about numbers


JavaScript booleans
Booleans are often used in conditional testing. Booleans can only have two values: true or false.
var x = true;
var y = false;
More about booleans
JavaScript arrays
JavaScript arrays are written with square brackets. Array items are separated by commas. Array
indexes are zero-based, which means the first item is [0], second is [1], and so on.

var cars = ["Saab", "Volvo", "BMW"];


More about arrays
JavaScript objects
JavaScript objects are written with curly braces. Object properties are written as name:value
pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
More about objects
The typeof operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable:
typeof
typeof
typeof
typeof
typeof

"John"
3.14
false
[1,2,3,4]
{name:'John', age:34}

//
//
//
//
//

Returns
Returns
Returns
Returns
Returns

string
number
boolean
object
object

Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also
undefined.
var person;

// Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
person = undefined;

// Value is undefined, type is undefined

Empty values
An empty value has nothing to do with undefined. An empty string variable has both a value and
a type.
var car = "";

// The value is "", the typeof is string

Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately,
in JavaScript, the data type of null is an object.
var person = null;
object

// Value is null, but type is still an

Difference Between Undefined and Null


typeof undefined
typeof null
null === undefined
null == undefined

5.

//
//
//
//

undefined
object
false
true

JavaScript operators

JavaScript arithmetic operators


Arithmetic operators are used to perform arithmetic on numbers (literals or variables).
Operator Description
+

Addition

Subtraction

Multiplication

Division

Modulus

++

Increment

--

Decrement

JavaScript assignment operators


Assignment operators assign values to JavaScript variables.
Operator Example Same as
=

x=y

x=y

+=

x += y

x=x+y

-=

x -= y

x=x-y

*=

x *= y

x=x*y

/=

x /= y

x=x/y

%=

x %= y

x=x%y

JavaScript comparison and logical operators

Operator Description
==

equal to

===

equal value and equal type

!=

not equal

!==

not equal value or not equal type

>

greater than

<

less than

>=

greater than or equal to

<=

less than or equal to

6.

JavaScript functions

A JavaScript function is a block of code designed to perform a particular task. A JavaScript


function is executed when "something" invokes it (calls it).
function myFunction(p1, p2) {
return p1 * p2;
p1 and p2
}

// The function returns the product of

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables). The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly
brackets: {}
When JavaScript reaches a return statement, the function will stop executing. If the function was
invoked from a statement, JavaScript will "return" to execute the code after the invoking
statement. Functions often compute a return value. The return value is "returned" back to the
"caller":
var x = myFunction(4, 3);
will end up in x
function myFunction(a, b) {
return a * b;
and b
}
The result in x will be: 12.

// Function is called, return value

// Function returns the product of a

Why functions?
You can reuse code: Define the code once, and use it many times. You can use the same code
many times with different arguments, to produce different results.
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);

In JavaScript, you can use functions the same way as you use variables.
var text = "The temperature is " + toCelsius(32) + " Centigrade";
instead of:
var x = toCelsius(32);
var text = "The temperature is " + x + " Centigrade";

7.

Declaring a class

When creating a script to use objects, you need to design a composite of data and code called a
class. Each new object based on this class is called an instance of that class. The data
associated with an object are called its properties, while the functions it uses are called
methods.
Lets look at how to declare the class for an object called User that will contain details about the
current user. To create the class, just write a function named after the class. This function can
accept arguments and can create properties and methods for the objects in that class. The
function is called a constructor.
<script>
function User(forename, username, password) {
this.forename = forename;
this.username = username;
this.password = password;
this.showUser = function() {
document.write("Forename: " + this.forename + "<br />");
document.write("Username: " + this.username + "<br />");
document.write("Password: " + this.password + "<br />");
}
}
</script>

The function is different from other functions in two ways:


It refers to an object named this. When the program creates an instance of User by
running this function, this refers to the instance being created. The same function can be
called over and over with different arguments, and will create a new User each time with
different values for the properties forename, and so on.
A new function named showUser is created within the function. The syntax shown here
is new and rather complicated, but its purpose is to tie showUser to the User class.
Thus, showUser comes into being as a method of the User class.

Creating an object
To create an instance of the class User, you can use a statement such as the following:
details = new User("Wolfgang", "w.a.mozart", "composer");
Or you can create an empty object, like this:
details = new User();
and then populate it later, like this:
details.forename = "Wolfgang";
details.username = "w.a.mozart";
details.password = "composer";
You can also add new properties to an object, like this:
details.greeting = "Hello";

Accessing objects
To access an object, you can refer to its properties, as in the following two unrelated example
statements:
name = details.forename;
if (details.username == "Admin") loginAsAdmin();
So to access the showUser method of an object of class User, you would use the following
syntax, in which the object details has already been created and populated with data:
details.showUser();
Assuming the data supplied earlier, this code would display:
Forename: Wolfgang
Username: w.a.mozart
Password: composer

The prototype keyword


The prototype keyword can save you a lot of memory. In the User class, every instance will
contain the three properties and the method. Therefore, if you have 1,000 of these objects in
memory, the method showUser will also be replicated 1,000 times. However, because the
method is identical in every case, you can specify that new objects should refer to a single
instance of the method instead of creating a copy of it. So, instead of using the following in a
class constructor:
this.showUser = function();
you could replace it with this:
User.prototype.showUser = function();
<script>
function User(forename, username, password) {
this.forename = forename;
this.username = username;
this.password = password;
User.prototype.showUser = function() {
document.write("Forename: " + this.forename + "<br />");
document.write("Username: " + this.username + "<br />");
document.write("Password: " + this.password + "<br />");
}
}
</script>

8.

JavaScript events

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML
pages, JavaScript can "react" on these events. Often, when events happen, you may want to do
something. JavaScript lets you execute code when events are detected. HTML allows event
handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a button element:
<button onclick='getElementById("demo").innerHTML=Date()'>The time
is?</button>
Here is a list of some common HTML events:
Event

Description

onchange

An HTML element has been changed

onclick

The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element


onmouseout

The user moves the mouse away from an HTML element

onkeydown

The user pushes a keyboard key

onload

The browser has finished loading the page

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...

9.

JavaScript regular expressions

A regular expression is a sequence of characters that forms a search pattern. When you search
for data in a text, you can use this search pattern to describe what you are searching for. A
regular expression can be a single character, or a more complicated pattern. Regular
expressions can be used to perform all types of text search and text replace operations.
var patt = /javascript/i
Example explained:
/javascript/i is a regular expression.
javascript is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
The search() method uses an expression to search for a match, and returns the position of the
match.
The replace() method returns a modified string where the pattern is replaced.
Use a regular expression to do a case-insensitive search for "javascript" in a string:
var str = "I am learning JavaScript.";
var n = str.search(/javascript/i);
The result will be: 14.
Use a string to do a search for "JavaScript" in a string:
var str = "I am learning JavaScript.";
var n = str.search("JavaScript");
Use a case insensitive regular expression to replace PHP with JavaScript in a string:
var str = "I am learning PHP.";
var res = str.replace(/php/i, "JavaScript");

The result will be: I am learning JavaScript.


The replace() method will also accept a string as search argument:
var str = "I am learning PHP.";
var res = str.replace("PHP", "JavaScript");

Regular expression modifiers


Modifiers can be used to perform case-insensitive more global searches:
Modifier Description
i

Perform case-insensitive matching

Perform a global match (find all matches rather than stopping after the first match)

Perform multiline matching

Regular expression patterns


Brackets are used to find a range of characters:
Expression Description
[abc]

Find any of the characters between the brackets

[0-9]

Find any of the digits between the brackets

(x|y)

Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:


Metacharacter Description
\d

Find a digit

\s

Find a whitespace character

\b

Find a match at the beginning or at the end of a word

\uxxxx

Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers define quantities:

Quantifier Description
n+

Matches any string that contains at least one n

n*

Matches any string that contains zero or more occurrences of n

n?

Matches any string that contains zero or one occurrences of n

Using the RegExp object


In JavaScript, the RegExp object is a regular expression object with predefined properties and
methods.
The test() method is a RegExp expression method. It searches a string for a pattern, and
returns true or false, depending on the result. The following example searches a string for the
character "e":
var patt = /e/;
patt.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be: true.
The exec() method is a RegExp expression method. It searches a string for a specified pattern,
and returns the found text. If no match is found, it returns null. The following example searches
a string for the character "e":
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be: e.
More about RegExp

10.

JavaScript errors

When executing JavaScript code, different errors can occur. Errors can be coding errors made
by the programmer, errors due to wrong input, and other unforeseeable things. To handle these
errors use throw and try to catch:
the try statement lets you test a block of code for errors;
the catch statement lets you handle the error;
the throw statement lets you create custom errors;
the finally statement lets you execute code, after try and catch, regardless of the result.
try {
Block of code to try
}
catch(err) {

Block of code to handle errors


}
finally {
Block of code to be executed regardless of the try / catch result
}

Input Validation Example


This example examines input. If the value is wrong, an exception (err) is thrown. The exception
(err) is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="number" min="5" max="10" step="1">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>

11.

JavaScript JSON (JavaScript Object Notation)

JSON is an open standard format that uses human-readable text to transmit data objects
consisting of attributevalue pairs. It is used primarily to transmit data between a server and
web application, as an alternative to XML.
The following JSON syntax defines an employees object: an array of 3 employee records
(objects):
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
The JSON format is syntactically identical to the code for creating JavaScript objects. Because
of this similarity, a JavaScript program can easily convert JSON data into native JavaScript
objects.

Converting a JSON text to a JavaScript object


First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript
object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

12.

The Document Object Model (DOM)

With the HTML DOM, JavaScript can access and change all the elements of an HTML
document. When a web page is loaded, the browser creates a Document Object Model of the
page. The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
can change all the HTML elements in the page
can change all the HTML attributes in the page
can change all the CSS styles in the page
can remove existing HTML elements and attributes
can add new HTML elements and attributes
can react to all existing HTML events in the page
can create new HTML events in the page

The HTML DOM document


In the HTML DOM object model, the document object represents your web page. The document
object is the owner of all other objects in your web page. If you want to access objects in an
HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate
HTML.
Finding HTML Elements
Method

Description

document.getElementById()

Find an element by element id

document.getElementsByTagName()

Find elements by tag name

document.getElementsByClassName() Find elements by class name


Changing HTML Elements
Method

Description

element.innerHTML=

Change the inner HTML of an element

element.attribute=

Change the attribute of an HTML element

element.setAttribute(attribute,value) Change the attribute of an HTML element


element.style.property=

Change the style of an HTML element

Adding and Deleting Elements


Method

Description

document.createElement() Create an HTML element


document.removeChild()

Remove an HTML element

document.appendChild()

Add an HTML element

document.replaceChild()

Replace an HTML element

document.write(text)

Write into the HTML output stream

Adding Events Handlers


Method

Description

document.getElementById(id).onclick=function(){code} Adding event handler code to an


onclick event
Examples
The easiest way to find an HTML element in the DOM, is by using the element id. This example
finds the element with id="intro":
var x = document.getElementById("intro");
This example finds all <p> elements:
var x = document.getElementsByTagName("p");
This example returns a list of all elements with class="intro".
var x = document.getElementsByClassName("intro");
This example returns a list of all <p> elements with class="intro".
var x = document.querySelectorAll("p.intro");
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<!DOCTYPE html>
<html>

<body>
<script>
document.write(Date());
</script>
</body>
</html>
This example changes the content of a <p> element:
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute=new value

The following example changes the style of a <p> element:


<html>
<body>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style

AJAX (Asynchronous JavaScript and XML)


1. What is AJAX
AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be
updated asynchronously by exchanging small amounts of data with the server behind the
scenes. This means that it is possible to update parts of a web page, without reloading the
whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How it works
AJAX cannot work independently, it is based on internet standards, and uses a combination of:
XMLHttpRequest object (to exchange data asynchronously with a server)
JavaScript/DOM (to display/interact with the information)
CSS (to style the data)
XML (often used as the format for transferring data)

2.

The XMLHttpRequest object

All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).
The XMLHttpRequest object is used to exchange data with a server behind the scenes.
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in
XMLHttpRequest object. To handle all modern browsers, including IE5 and IE6, check if the
browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if
not, create an ActiveXObject:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

3.

AJAX request

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Method

Description

open(method,url,async) Specifies the type of request, the URL, and if the request should be
handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)

Sends the request off to the server.


string: Only used for POST requests

GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server)
Sending a large amount of data to the server (POST has no size limitations)

Sending user input (which can contain unknown characters), POST is more robust and
secure than GET

GET requests
A simple GET request:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
If you want to send information with the GET method, add the information to the URL:
xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();

POST requests
A simple POST request:
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the
data you want to send in the send() method:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-formurlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Method

Description

setRequestHeader(header,value) Adds HTTP headers to the request.


header: specifies the header name
value: specifies the header value

The url - a file on a server


The url parameter of the open() method, is an address to a file on a server:

xmlhttp.open("GET","ajax_test.asp",true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php
(which can perform actions on the server before sending the response back).

Asynchronous - true or false?


AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to
behave as AJAX, the async parameter of the open() method has to be set to true:
xmlhttp.open("GET","ajax_test.asp",true);
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks
performed on the server are very time consuming. Before AJAX, this operation could cause the
application to hang or stop.
With AJAX, the JavaScript does not have to wait for the server response, but can instead:
execute other scripts while waiting for server response
deal with the response when the response ready
When using async=true, specify a function to execute when the response is ready in the
onreadystatechange event:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
To use async=false, change the third parameter in the open() method to
false:
xmlhttp.open("GET","ajax_info.txt",false);
Using async=false is not recommended, but for a few small requests this can be ok.
Remember that the JavaScript will NOT continue to execute, until the server response is ready.
If the server is busy or slow, the application will hang or stop.
Note: When you use async=false, do NOT write an onreadystatechange function - just put the
code after the send() statement:
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Server response
To get the response from a server, use the responseText or responseXML property of the
XMLHttpRequest object.
Property

Description

responseText

get the response data as a string

responseXML get the response data as XML data

The responseText property


If the response from the server is not XML, use the responseText property. The responseText
property returns the response as a string, and you can use it accordingly:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

The responseXML property


If the response from the server is XML, and you want to parse it as an XML object, use the
responseXML property:
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;

jQuery
1. What is jQuery
jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to
make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that
require many lines of JavaScript code to accomplish, and wraps them into methods that you can
call with a single line of code. jQuery also simplifies a lot of the complicated things from
JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities

Why jQuery?
There are lots of other JavaScript frameworks out there, but jQuery seems to be the most
popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
Google
Microsoft
IBM
Netflix

2.

Adding jQuery to Your Web Pages

There are several ways to start using jQuery on your web site. You can:

Download the jQuery library from jQuery.com


Include jQuery from a CDN, like Google

Downloading jQuery
There are two versions of jQuery available for downloading:

Production version - this is for your live website because it has been minified and
compressed
Development version - this is for testing and development (uncompressed and readable
code)
Both versions can be downloaded from jQuery.com.
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>

jQuery CDN
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).
Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the following:
Google CDN:
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
></script>
</head>
Microsoft CDN:
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery1.11.2.min.js"></script>
</head>

3.

jQuery syntax

The jQuery syntax is tailor made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()


A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

The document ready event


Generally, all jQuery methods are used inside a document ready event:
$(document).ready(function() {
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is
ready).
It is good practice to wait for the document to be fully loaded and ready before working with it.
This also allows you to have your JavaScript code before the body of your document, in the
head section.
Here are some examples of actions that can fail if methods are run before the document is fully
loaded:
Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet
Tip: The jQuery team has also created an even shorter method for the document ready event:
$(function() {
// jQuery methods go here...
});
Use the syntax you prefer. We think that the document ready event is easier to understand
when reading the code.

4.

jQuery Selectors

jQuery selectors allow you to select and manipulate HTML element(s).


jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().

The element selector


The jQuery element selector selects elements based on the element name. You can select all
<p> elements on a page like this: $("p").
When a user clicks on a button, all <p> elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

The #id selector


The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id
should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element: $("#test").
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

The .class selector


The jQuery class selector finds elements with a specific class. To find elements with a specific
class, write a period character, followed by the name of the class: $(".test").
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();

});
});

More examples of jQuery selectors


Syntax

Description

$("*")

Selects all elements

$(this)

Selects the current HTML element

$("p.intro")

Selects all <p> elements with class="intro"

$("p:first")

Selects the first <p> element

$("ul li:first")

Selects the first <li> element of the first <ul>

$("ul li:first-child")

Selects the first <li> element of every <ul>

$("[href]")

Selects all elements with an href attribute

$("a[target='_blank']")

Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to
"_blank"
$(":button")

Selects all <button> elements and <input> elements of type="button"

$("tr:even")

Selects all even <tr> elements

$("tr:odd")

Selects all odd <tr> elements

5.

jQuery Event Methods

All the different visitor's actions that a web page can respond to are called events. An event
represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element
Here are some common DOM events:
Mouse events Keyboard events Form events Document/Window Events
click

keypress

submit

load

dblclick

keydown

change

resize

mouseenter

keyup

focus

scroll

blur

unload

mouseleave

In jQuery, most DOM events have an equivalent jQuery method. To assign a click event to all
paragraphs on a page, you can do this:
$("p").click(function(){
// action goes here!!
});

Commonly used jQuery event methods


The click() method attaches an event handler function to an HTML element. The function is
executed when the user clicks on the HTML element. The following example says: When a click
event fires on a <p> element; hide the current <p> element:
$("p").click(function(){
$(this).hide();
});

The dblclick() method attaches an event handler function to an HTML element. The function is
executed when the user double-clicks on the HTML element:
$("p").dblclick(function(){
$(this).hide();
});

The mouseenter() method attaches an event handler function to an HTML element. The
function is executed when the mouse pointer enters the HTML element:
$("#p1").mouseenter(function(){
alert("You entered p1!");
});

The mouseleave() method attaches an event handler function to an HTML element. The
function is executed when the mouse pointer leaves the HTML element:
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});

The mousedown() method attaches an event handler function to an HTML element. The
function is executed, when the left mouse button is pressed down, while the mouse is over the
HTML element:
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});

The mouseup() method attaches an event handler function to an HTML element. The function
is executed, when the left mouse button is released, while the mouse is over the HTML element:
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});

The hover() method takes two functions and is a combination of the mouseenter() and
mouseleave() methods. The first function is executed when the mouse enters the HTML
element, and the second function is executed when the mouse leaves the HTML element:
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});

The focus() method attaches an event handler function to an HTML form field. The function is
executed when the form field gets focus:
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});

The blur() method attaches an event handler function to an HTML form field. The function is
executed when the form field loses focus:
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});

The on() method


The on() method attaches one or more event handlers for the selected elements. Attach a click
event to a <p> element:

$("p").on("click", function(){
$(this).hide();
});
Attach multiple event handlers to a <p> element:
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});

Você também pode gostar