Professional Documents
Culture Documents
Ajax-Json Jquery Slides
Ajax-Json Jquery Slides
Chen-Hsiang (Jones) Yu
chyu@mit.edu
http://chyu.scripts.mit.edu/ajax-json-jquery-examples.zip
p
y
p
j j
jq y
p
p
Jan. 5, 2010
6.470
Understand
Understand
Understand
Understand
Jan. 5, 2010
6.470
Outline
AJAX
JSON
jQuery
Jan. 5, 2010
6.470
Prerequisites
MIT SIPB Web Script Service
http://scripts.mit.edu/web/
http://scripts mit edu/web/
Instructions:
o Using any terminal to connect to Athena
o athena% add scripts
athena% signup-web
o Your web space will be at http://username.scripts.mit.edu/
o You can use any FTP client to upload your files and scripts
FTP client:
Filezilla (Windows/Linux/Mac)
o http://filezilla-project.org/download.php
Alternative: OpenAFS - http://www.openafs.org/
Jan. 5, 2010
6.470
AJAX
Jan. 5, 2010
6.470
AJAX - 1
It stands for Asynchronous JavaScript and XML
It was first mentioned by Jesse James Garrett in 2005. [1]
It is not a new technology. It is several technologies. [1]
Jan. 5, 2010
6.470
AJAX - 2
Intuition: Static web site vs. AJAX site
AJAX engine: XMLHttpRequest object
Jan. 5, 2010
6.470
AJAX - 3
AJAX - 4
a.
b.
c
c.
abandon
v./n.
to give up completely
abash
v.
to make embarrassed
SQL Query
Web Browser
data
Database
1. mySQL
Script Languages
1 PHP
1.
Content:
C
t t
1. HTML Document
2. XML Document
3. JSON Document
Jan. 5, 2010
6.470
AJAX - 5
POST and GET calls in AJAX [2]
GET call in AJAX still has the size limitation on the amount of data that
can be passed.
passed
General principle:
o GET method: it is used to retrieve data to display in the page and the
data is not expected to be changed on the server.
o POST method: it is used to update
p
information on the server.
Jan. 5, 2010
6.470
10
Exercise: Example 1
letters
A
B
C
abandon
v./n.
to give up completely
content
abash
v.
to make embarrassed
letter
6.470
11
<?php
print '<div class="entry">
<h3 class="term">ABANDON</h3>
<div
div class
class="part">v
part v./n.
/n </div>
/div
<div class="definition">
to give up completely
</div>
</div>
<div class="entry">
<h3 class="term">ABASH</h3>
<div class="part">v.</div>
<div class="definition">
to make embarrassed
</div>
</div>
</div>
';;
?>
example1.php
http://chyu.scripts.mit.edu/example1.php
Jan. 5, 2010
6.470
12
<html>
<head>
<link rel="stylesheet" href="example1.css" type="text/css"/>
<script type="text/javascript">
AJAX 6
function sendRequest(url){
Example
ajax1
= ajaxCreate();
if(!ajax){
alert("Browser is not compatable with XMLHttpRequest");
return 0;
}
var ajax;
ffunction
ti ajaxCreate(){
j C t (){
if(window.XMLHttpRequest){
//For IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {
//For IE6
IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function receiveData(){
if(ajax.readyState == 4){
if(ajax.status == 200){
var content = document.getElementById('content');
content.innerHTML = ajax.responseText;
}else{
alert("Server process error");
}
}
}
ajax.onreadystatechange = receiveData;
ajax.open("GET", url, true);
ajax.send(null);
}
</script>
</head>
<body>
<div class="letters">
<div class="letter" id="letter-a">
<h3>
<a href="javascript:sendRequest('example1.php')">A</a>
</h3>
</div>
</div>
<div id="content"></div>
</body>
</html>
example1.html
http://chyu.scripts.mit.edu/example1.html
Jan. 5, 2010
6.470
13
AJAX - 5
Properties
Description [3]
onreadystatechange
y
g
A JavaScript
p function object
j
that is called whenever the readyState
y
attribute
changes. The callback is called from the user interface thread.
readyState
State
Description
UNINITIALIZED
LOADING
LOADED
send() has been called, and headers and status are available.
INTERACTIVE
COMPLETED
responseText
The response to the request as text, or null if the request was unsucessful or has
not yet been sent.
responseXML
The response to the request as a DOM Document object, or null if the request was
unsuccessful,
ns ccessf l has not yet
et been sent,
sent or
o cannot be parsed
pa sed as XML.
XML The response
esponse is
parsed as if it were a text/xml stream.
status
The status of the response to the request. This is the HTTP result code (for
example, status is 200 for a successful request).
statusText
The response string returned by the HTTP server. Unlike status, this includes the
entire text of the response message ("200 OK", for example).
Jan. 5, 2010
6.470
14
AJAX - 6
Methods
Description [3]
Abort()
getAllResponseHeaders()
getResponseHeader("headerLabel")
send(content)
(
)
setRequestHeader("label", "value")
Jan. 5, 2010
6.470
15
Jan. 5, 2010
6.470
16
JSON
Jan. 5, 2010
6.470
17
JSON - 1
Text is a data transmission format on the Internet
A need to transmit complicated (structured) data
Book info, movie info, etc.
Idea:
Encode data
Transmit in text format
Decode data
Jan. 5, 2010
6.470
18
JSON - 2
It stands for JavaScript Object Notation and it is a textb
based
dd
data
t iinterchange
t
h
fformat.
t [4]
JSON is built on two structures:
j
A collection of name and value p
pairs
Object:
Array: An ordered list of values
6.470
19
Explanation
object with one member
Examples
{
}
{
}
"course-name": "6.470
"course-name":
"course
name": "6
"6.470",
470"
"units": 6
"course-name": "6.470",
"times": ["12-4","12-4", "12-4"]
"John":
John :
{
"label":"John",
"data":[[1880,0.081536],[1881,0.08098],[1882,0.078308]]
},
"James":
{
"label":"James",
"data":[[1880,0.050053],[1881,0.05025],[1882,0.048278]]
}
6.470
20
JSON - 3
Examples:
{
}
{
"course-name : "6.470
"course-name : "6.470",
"times": ["12-4","12-4", "12-4"]
6.470
21
JSON - 4
"data":[[1880
data :[[1880,0.081536],[1881,0.08098],[1882,0.078308]]
0 081536] [1881 0 08098] [1882 0 078308]]
6.470
22
JSON - 5
Why JSON format is easier to be evaluated?
var a = {
Jan. 5, 2010
"John":
{
"label":"John",,
"data":[[1880,0.081536],[1881,0.08098],[1882,0.078308]]
},
"James":
{
"label":"James"
label : James ,
"data":[[1880,0.050053],[1881,0.05025],[1882,0.048278]]
}
6.470
23
Exercise: Example 2
letters
A
B
C
abandon
v./n.
to give up completely
content
abash
v.
to make embarrassed
letter
Jan. 5, 2010
6.470
24
function receiveData(){
(){
if(ajax.readyState == 4){
if(ajax.status == 200){
var data = [
{ "word":"ABANDON",
"function":"v
function : v./n.
/n ",
"definition":"to give up completely"},
{ "word":"ABASH",
"function":"v.",
"definition":"to make embarrassed"}
];
Wh t is
What
i the
th problem?
bl ?
example2.html
</script>
Jan. 5, 2010
6.470
25
Wh t is
What
i the
th problem?
bl ?
Jan. 5, 2010
6.470
26
<script type="text/javascript">
function receiveData(){
if( j
if(ajax.readyState
d St t == 4){
if(ajax.status == 200){
var data = [
{ "word":"ABANDON",
"function":"v./n.",
"definition":"to
definition : to give up completely"}
completely },
{ "word":"ABASH",
"function":"v.",
"definition":"to make embarrassed"}
];
var output = "";
for(each in data){
output += '<div class="entry">';
output += '<h3 class="word">' + data[each].word + '</h3>';
output += '<div class="function">' + data[each].function + '</div>';
output
t t += '<div
' di class="definition">'
l
"d fi iti " ' + d
data[each].definition
t [
h] d fi iti + ''</div>';
/di '
output += '</div>';
}
var content = document.getElementById('content');
content innerHTML = output;
content.innerHTML
}else{
alert("Server process error");
}
}
}
</script>
Jan. 5, 2010
example2-sol.html
p
http://chyu.scripts.mit.edu/example2-sol.html
6.470
27
Jan. 5, 2010
6.470
28
jQuery
query ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ?
Jan. 5, 2010
6.470
29
jQuery - 1
JavaScript libraries and frameworks
Advantages
Jan. 5, 2010
6.470
30
jQuery - 2
jQuery: A JavaScript library was released by John Resig in 2006
Idea: Putting together a set of functions
Navigate a document
Event handling
Create animations
Ajax development
Extendibility: plugins
Jan. 5, 2010
6.470
31
jQuery - 3
Usage:
Jan. 5, 2010
6.470
32
jQuery - 4
APIs:
jQuery core
jQ
Selectors
Attributes
T
Traversing
i
Manipulation
CSS
E
Events
t
Effects
Ajax
Utiliti
Utilities
jQuery UI
Jan. 5, 2010
6.470
33
jQuery - 5
APIs:
jQuery core
jQ
Selectors
Attributes
T
Traversing
i
Manipulation
CSS
E
Events
t
Effects
Ajax
Utiliti
Utilities
jQuery UI
Jan. 5, 2010
6.470
34
jQuery - 6
Core:
jQuery functions:
o $(expression, [context])
$(input:radio, document.form[0])
o $(html)
$('<div
$(' di id
id=loading">Loading...</div>')
l di " L di
/di ')
o $(elements)
$(document.body).css(background,
$(document body) css(background red);
o $(callback)
$(function(){alert(
$(function(){alert(test);})
test );})
Jan. 5, 2010
6.470
35
jQuery - 7
Selectors:
Types:
o Basic:
element,
l
t #id
#id, class,
l
.classA.classB
l
A l
B
Ex: $(p), $(#id), $(.class), $(.classA.classB)
o Hierarchy:
ancestor decendent, parent > child, prev + next
Ex: $(
$(form
form input
input)), $(
$(#main
#main > *)), $(label
$( label + input)
input )
Jan. 5, 2010
6.470
36
jQuery - 8
o Form:
Selectors
Matched Elements
:input
:button
o Basic filters:
:first , :last , :not(selector) , :even , :odd , :eq(index) ,
:gt(index) , :lt(index) , :header , :animated
o Attribute filters:
[attribute] , [attribute!=value] , [attribute^=value] ,
[attribute$=value] , [attribute*=value], [filter1][filter2]
Jan. 5, 2010
6.470
37
jQuery - 9
Attributes:
Attr:
o attr(name), attr(properties) attr(key,value), removeAttr(name)
Class:
o addClass(class), removeClass(class), toggleClass(class)
HTML:
o html(), html(value)
Text:
o text(), text(value)
Value:
o val(), val(value)
Jan. 5, 2010
6.470
38
jQuery - 10
Events:
Page load:
l d
o ready(fn)
Event handling:
o bind(type, fn), unbind(type, fn), trigger(event)
Event helpers:
o click(), click(fn), mousedown(fn), mouseout(fn),
Effects:
Basics:
o show(),
show() show(speed)
show(speed), hide(),
hide() toggle(),
toggle() toggle(speed)
Fading:
o fadeIn(speed), fadeOut(speed), fadeTo(speed, opacity)
Jan. 5, 2010
6.470
39
Exercise: Example 3
content
A SCANDAL IN BOHEMIA
I.
Requirement:
o Using jQuery selectors, attributes, events
o When clicking font symbols (small, medium,
large) the content of paragraphs can change
large),
properly.
II.
At three o'clock precisely I was at Baker Street, but
Holmes had not yet returned. The landlady informed me
that he had left the house shortly after eight o'clock in
the morning. ..
example3.html
p
http://chyu.scripts.mit.edu/example3.html
Jan. 5, 2010
6.470
40
<script type="text/javascript">
$(document).ready(function(){
$('#large').bind(click, function(){
$('p').removeClass().addClass('large');
});
$('#medium').bind(click, function(){
$('p').removeClass().addClass('medium');
});
$('#small').bind(click, function(){
$('p').removeClass().addClass('small');
});
// Set default font size as medium
$('#medium').trigger('click');
});
example3-sol.html
p
</script>
Jan. 5, 2010
http://chyu.scripts.mit.edu/example3-sol.html
6.470
41
Exercise: Example 3
6.470
42
jQuery - 11
Ajax:
Ajax Request:
o $.ajax(options) => options: a set of key/value pairs
o $.get(url, [data], [callback], [type])
o $.post(url, [data], [callback], [type])
o $.getJSON(url, [data], [callback], [type])
o $.getScript(url, [callback])
$.ajax(
{
url: process.php",
type: "POST",
data: class=6470&name=Tim",
class 6470&name Tim ,
success: function(msg){
alert(Data:" + msg );
}
}
)
);
Jan. 5, 2010
$.post(
$
post(
"test.php",
{
func: "getNameAndTime"
},
function(data){
alert(data.name);
alert(data.time);
},
"json
json
);
6.470
43
jQuery - 12
$
$.getJSON(
tJSON(
"http://api.flickr.com/services/feeds/photos_public.gne?tags=doggy&format=json&jsoncallback=?",
function(data){
$ each(data items function(i,item){
$.each(data.items,
f nction(i item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 2 ) return false;
}
);
}
);
Jan. 5, 2010
6.470
44
jQuery - 13
Ajax Events:
o ajaxComplete(callback), ajaxStart(callback), ajaxStop(callback),
ajaxSend(callback), ajaxError(callback), ajaxSuccess(callback)
o Ex:
$('<div
$(
div id="loading">Loading...</div>')
id loading Loading... /div )
.insertBefore("#images")
.ajaxStart(
(){
function(){
$(this).show();
}
j
).ajaxStop(
function(){
$(this).hide();
}
);
Jan. 5, 2010
6.470
45
Exercise: Example 4
a.
b.
c.
abandon
v./n.
to give up completely
abash
v.
to make embarrassed
Jan. 5, 2010
6.470
46
Exercise: Example 4
<?php
Jan. 5, 2010
$data = '
[
{
"word": "ABANDON",
"function": "v./n.",
"definition": "to give up completely"
},
{
"word": "ABASH",
"function": "v.",
"definition": "to make embarrassed"
},
{
"word": "ABATE",
"function": "v.",
"definition": "to make less in amount; wane"
},
{
"word": "ABBREVIATE",
"function": "v.",
"definition": "to make shorter; to shorten a word or phrase"
example4.php
}
]
http://chyu.scripts.mit.edu/example4.php
';
print($_GET['callback'].'('.$data.')');
?>
6.470
47
<script type="text/javascript">
$(document).ready(function(){
(
)
y(
()
var url="example4.php";
Part 1
$('#letter-a').click(function(){
1st
parameter
2nd parameter
$.getJSON(
urll + '?
'?callback=?',
llb k ?'
function(data){
$('#content').empty();
$.each(data, function(index, entry){
var html = '<div class="entry">';
html +
+= '<h3
<h3 class
class="word">'
word > + entry[
entry['word']
word ] + '</h3>';
</h3> ;
html += '<div class="function">' + entry['function'] + '</div>';
html += '<div class="definition">' + entry['definition'] + '</div>';
html += '</div>';
$('#content').fadeIn().append(html);
});
});
return false;
});
});
</script>
Jan. 5, 2010
example4.html
http://chyu.scripts.mit.edu/example4.html
6.470
48
<script type=
type="text/javascript">
text/javascript >
$(document).ready(function(){
Part 2
example4.html
http://chyu.scripts.mit.edu/example4.html
Jan. 5, 2010
6.470
49
<script type="text/javascript">
$(document).ready(function(){
var url="example4.php";
$('#letter-a').click(function(){
$.getJSON(url + '?callback=?', function(data){
$('#content').empty();
$.each(data, function(index, entry){
var html = '<div class="entry">';
html += '<h3 class="word">' + entry['word'] + '</h3>';
html +=
+ '<div
<div class
class="function">'
function > + entry[
entry['function']
function ] + '</div>';
</div> ;
html += '<div class="definition">' + entry['definition'] + '</div>';
html += '</div>';
$('#content').fadeIn().append(html);
});
});
return false;;
});
Complete Version
example4.html
Jan. 5, 2010
6.470
50
Jan. 5, 2010
6.470
51
References
[1] Ajax: A New Approach to Web Applications.
http://www.adaptivepath.com/ideas/essays/archives/000385.php
[2] AJAX - Get
G t or P
Post.
t http://javascript.about.com/od/ajax/a/ajaxgp.htm
htt //j
i t b t
/ d/ j / / j
ht
[3] Mozilla XMLHttpRequest. https://developer.mozilla.org/en/XMLHttpRequest
[4] Introducing JSON. http://www.json.org/index.html
[5] 6.470 2009 IAP - AJAX with jQuery. http://6.470.scripts.mit.edu/2009/
[[6]] Websites using
g jQ
jQuery,
y, ordered by
y popularity.
p p
y http://www.backendbattles.com/backend/jQuery
p //
/
/jQ
y
[7] Project Gutenberg - The Adventures of Sherlock Holmes. http://www.gutenberg.org/etext/1661
[8] Jonathan Chaffer and Karl Swedberg, Learning jQuery 1.3, PACKT publishing, 2009.
Jan. 5, 2010
6.470
52