CS 520 Web Programming Introduction to Ajax and
CS 520 Web Programming Introduction to Ajax and j. Query Chengyu Sun California State University, Los Angeles
The Desktop Experience
The Desktop Advantage Large selection of GUI components Interactive n Rich event model Responsive n Partial redraw
HTML Event Models HTML 4 Event Model n n HTML 4. 01 Specification http: //www. w 3. org/TR/REChtml 40/interact/scripts. html#h-18. 2. 3 Limited but widely supported Standard Event Model n DOM Level 2 HTML Specification http: //www. w 3. org/TR/DOM-Level-2 Events/events. html Browser specific event models
Events and Event Handler Events n onfocus, onblur, onkeypress, onkeydown, onkeyup, onclick, ondbclick, onmousedown, onmouseup, onmousemove, onmouseover … Specify event handler n n <element event=“code”> For example: <button onclick="click. Handler(); ">click</button>
Example: Event Handling j 1. html n n Uses X Library from http: //crossbrowser. com/ Event handler w Written in Java. Script w Modify the HTML document
Java. Script Interpreted language Originally developed by Netscape Syntax is similar to Java Web Server Client-side Browser Core Server-side
Core Java. Script Mainly covers language syntax, which is similar to Java Some “un-Java-like” language features n n Object creation Functions as first-class citizens
Object Creation – Approach 1 var car = new Object(); car. make = ‘Honda’; car. model = ‘Civic’; car. year = 2001; var owner = new Object(); owner. name = ‘Chengyu’; car. owner = owner; A Java. Script object consists of a set of properties which can be added dynamically
Object Creation – Approach 2 var car = { make: ‘Honda’, model: ‘Civic’, year: 2001, owner: { name: ‘Chengyu’ } }; Object Literal
Object Creation – Approach 3 var car = { ‘make’: ‘Honda’, ‘model’: ‘Civic’, ‘year’: 2001, ‘owner’: { ‘name’: ‘Chengyu’ } }; JSON (Java. Script Object Notation)
Functions as First-class Citizens In Java. Script, functions are considered objects like other object types n n n Assigned to variables Assigned as a property of an object Passed as a parameter Returned as a function result Function literals (i. e. functions without names)
Function Examples function foo() { alert('foo'); } bar = function() { alert('bar'); } Regular function creation Function literal Function assignment set. Timeout( bar, 5000 ); Function as parameter set. Timeout( function() { alert(‘foobar’); }, 5000 ) Function literal as parameter
Client-Side Java. Script Embed Javs. Script in HTML n <script> w type=“text/javascript” w language=“Java. Script” w src=“path_to_script_file” Run inside a browser
Processing an HTML Document <html> <head><title>Java. Script Example</title></head> <body> <h 1>Java. Script Example</h 1> <p>Some content. </p> </body> </html> As a text file – very difficult As an object
Document Object Model (DOM) Representing documents as objects so they can be processed more easily by a programming language
DOM Representation document <html> <head> <title> “Java. Script Example” <body> <h 1> “Java. Script Example” <p> “Some content. ”
Manipulate a Document Find Elements Modify Elements Create Elements
Find Elements document. get. Element. By. Id() document. get. Elements. By. Name() document. get. Elements. By. Tag. Name()
Modify Elements. . . HTMLElement properites and methods n IE w inner. HTML w inner. Text w insert. Adjacent. HTML() w insert. Adjacent. Text() n Netscape/Mozilla w inner. HTML n Element-specific
. . . Modify Elements node n n n set. Attribute(), remove. Attribute() append. Child(), remove. Child() insert. Before(), replace. Child()
Create Elements document n n create. Element() create. Text. Node()
Example: Document Manipulation j 2. html n n n Read and display the text input Display “Hello <name>”? ? Add text input to table? ?
Create Desktop-Like Web Applications Interactivity n n n HTML events Java. Script for event handling DOM for document manipulation Responsiveness? ?
Communicate with Server The synchronous request-response model is still a limiting factor in responsiveness Solution: XMLHttp. Request n A Java. Script object w Send request and receive response n Response can be handled asynchronously w Do not need to wait for the response
Understand Asynchronous … Synchronous Asynchronous send( request ); // wait for response // don’t wait for response process( response ); // do other things … What’s the problem? ? What’s the solution? ?
… Understand Asynchronous // callback function foo( response ) { process( response ); } Same as handling events like click. // set a callback function // which will be called // when the response comes // back … … send( request ); // do other things …
An XMLHttp. Request Example a 1. html n n n A client scripts sends an XMLHttp. Request A servlet responses with a random number When the message arrives on the client, a callback function is invoked to update the document
About the Example click. Handler() new. XMLHttp. Request() update. Document() get. Ready. State. Handler()
XMLHttp. Request - Properties onreadystatechange ready. State n n n 0 1 2 3 4 – – – uninitialized loading loaded interactive complete status. Text response. Body response. Stream response. Text response. XML
XMLHttp. Request - Methods abort() get. All. Response. Headers() get. Response. Header( header ) open( method, url, async. Flag, username, password ) n async. Flag, username, password are optional send( message. Body ) set. Request. Header( name, value )
So What is Ajax? Asynchronous Java. Script and XML n n http: //www. adaptivepath. com/ideas/essays /archives/000385. php Java. Script + XMLHttp. Request Characteristics of Ajax n n Non-blocking – the server response is handled asynchronously with a callback function Partial page update using Java. Script
More About AJAX XMLHttp. Request used to be an IE specific feature that received little attention It’s all started by Google Maps The beginning of “Web 2. 0”
Key Elements of an Ajax Operation Client Event handler n n n Create a XMLHttp. Request Attach a callback function Send the request Callback function n n Process the response Update the HTML Page Server Process the request Send back a response
Problems of Plain Java. Script + Xml. Http. Request Each browser has their own Java. Script implementation n Code that works on some browsers may not work on others Lack of pre-made GUI components Implementing Ajax operations is quite tedious
Java. Script/Ajax Frameworks and Libraries http: //en. wikipedia. org/wiki/List_of_Aja x_frameworks n Cross-browser compatibility w New Java. Script API, e. g. X Lib, JQuery w New language, e. g. ZK, Taconite n n Pre-made, Ajax-enabled GUI component Simplify the implementation of Ajax operations
One Library to Rule Them All j. Query - http: //jquery. com/ j. Query UI - http: //jqueryui. com/ The market share of j. Query n http: //trends. builtwith. com/javascript/javas cript-library
A j. Query Example j 3. html n n n Usage j. Query wrapper Selectors Elements Events and event handling DOM manipulation
Use j. Query Library http: //jquery. com/download/ n n Local copy vs. CDN hosted 1. x vs 2. x
j. Query Wrapper j. Query() or $() n Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. $( "input[name='first. Name']" ) $( "#who" ) $( "#t 1" ) Selector
Basic Selectors By id n $(“#foo”) By tag name n $(“div”) By CSS class n $(“. foo”) By attribute n n $(“[name]”) $(“[name=‘joe’]”)
Combine Selectors Select all the <div> elements with CSS class foo and an attribute bar $(“div. foo[bar]”) Select all the <div> elements, and all the elements with CSS class foo, and all the elements with an attribute bar $(“div, . foo, [bar]”)
Other Selectors and Filters Form selectors Hierarchy selectors Filters
What Can We Do With An Element Get and set n n Manipulate CSS html() attr() prop() val() n n add. Class() remove. Class() toggle. Class() has. Class() Property tag. Name <input name=“username” value=“cysun” /> Attribute name val()
Typical Event and Event Handling in j. Query Event Handler $("#click"). click( function(){. . . }); Unobtrusive Java. Script: separate style, behavior, and structure. <button id="click“ onclick="display(); "> Click Me</button>
Document Ready Event Triggered when the DOM hierarchy of the HTML document is fully constructed $( document ). ready( handler ) $( handler ) (not recommended)
Other Events Mouse events n . click(). dbclick() n … n Keyboard events n . keyup(). keydown(). keypress() n … n n Form events n . change(). submit() n … n Browser events n . resize() n … Document events
DOM Manipulation Insertion n Around (i. e. parent) Inside (i. e. children) Outside (i. e. sibling) Removal Replacement Example: $("#t 1"). append("<tr><td>John</td><td>Doe</td></tr>");
Example: j. Query Tic Tac Toe j 4. html O X
AJAX with j. Query http: //api. jquery. com/category/ajax/ $. ajax( url [, settings]) n n n url: request URL data: data to be sent to the server success: a function to be called if the request succeeds Example: a 2. html
- Slides: 50