COM531 Multimedia Technologies - PowerPoint PPT Presentation

1 / 99
About This Presentation
Title:

COM531 Multimedia Technologies

Description:

COM531 Multimedia Technologies Lecture 7 Flash AS and Flash Catalyst Ajax – PowerPoint PPT presentation

Number of Views:295
Avg rating:3.0/5.0
Slides: 100
Provided by: ISG94
Category:

less

Transcript and Presenter's Notes

Title: COM531 Multimedia Technologies


1
COM531 Multimedia Technologies
  • Lecture 7
  • Flash AS and Flash Catalyst
  • Ajax

2
What is Interactivity?
  • Automated response to user activity
  • Example applications
  • Reactive elements
  • Simulations
  • Tutorials
  • Quizzes
  • Interactivity in Flash
  • Events call actions to be performed on targets
  • Defined using ActionScript

3
Managing Flash Projects
  • Scenes
  • Divide timeline into manageable sections
  • e.g. Introduction, conclusion, index, etc.
  • Useful for long/complex movies
  • Libraries
  • Organise assets using folders
  • Share assets between projects
  • e.g. logos, audio/video
  • Movie Explorer
  • Overview of project structure
  • Access and edit assets

4
Testing Flash Movies
  • Bandwidth profiler
  • Test delivery with differentbandwidths
  • Identify download delays
  • Show streaming
  • Debug Movie
  • For validating complex scripts
  • Real time values for variables, movie clip
    properties
  • Test manually
  • Different platforms and browsers
  • Different connections (e.g. modem)

5
Publish Settings
  • Select formats for publication
  • Range of formats supported
  • Flash, HTML, GIF, QuickTime
  • Configure settings for each format
  • Filenames
  • Alignment
  • Size
  • Looping
  • Quality
  • Publish preview for each format
  • Test appearance and functionality

6
Publish as HTML
  • HTML is native language of web
  • Flash can automatically create HTML
  • Based on range of built-in templates
  • HTML produced not always appropriate
  • Change HTML of each page
  • Manually or with an authoring tool
  • Customise Flash templates
  • Affects all published pages

7
Flash Accessibility
  • Web content should be accessible to all users
  • Regardless of ability/disability
  • Issues
  • Visual, time-based media not suitable for all
    users
  • Requires Flash player (plug-in)
  • Limited support for screenreaders
  • Benefits
  • Animation can be more accessible to some users
  • Supports multiple media (audio, video, text)
  • Vector graphics scale without deterioration
  • Allows keyboard access
  • Player ensures cross-platform consistency

8
Improving Accessibility
  • Provide text equivalents in HTML
  • For entire movie using dlink
  • Provide text equivalents in Flash
  • Increases accessibility to screen readers
  • Specific software required to process
  • Only for movie clips
  • Provide keyboard controls to movies (play,
    stop)
  • Publish movie content in range of formats
  • Images, text, audio/video

9
Object-Oriented Scripting
  • ActionScript is an object-oriented scripting
    language
  • Scripting languages organise information into
    groups called classes
  • Classes and objects are just ways to group
    together chunks of information

10
Terminology
  • Class
  • Instance
  • Object

11
Classes objects
  • Classes are groups of objects that share
    characteristics, e.g. rectangles
  • Shared characteristics allow you to create a
    blueprint for those objects
  • A software blueprint for an object is called a
    class

12
Object-Oriented Scripting
  • You can create multiple instances of these
  • classes, which are called objects
  • Real-world analogy Bicycle" class
  • You can have many objects of the same kind (e.g.
    A bicycle, your bicycle is just one of many
    bicycles in the world)
  • Using object-oriented terminology, we say that
    your
  • bicycle object is an instance of the class of
    objects
  • known as bicycles

13
Object-oriented terminology
Class Defines the common characteristics of a
bicycle. Like a plan
Objects Physical manifestation of bicycle class.
Each object is a instance of the bicycle class
14
Instances
  • Using the bicycle class, you can create any
  • number of bicycle objects from the class
  • When you create an instance of a class each
  • instance gets its own copy of all the instance
  • variables defined in the class

15
Instances
16
Classes objects
  • Bicycles have states (current gear)
  • Bicycles have behaviors (change gears, brake) in
    common
  • However, each bicycle's state is independent of
  • and can be different from that of other bicycles

17
Objects vs. Classes
  • Objects and classes seem very similar
  • In the real world, it's obvious that classes are
    not themselves but the objects they describe
  • A blueprint of a bicycle is not a bicycle

18
Objects vs. Classes
19
Class Instances in Flash
20
Class Instance in Flash
21
Classes objects
  • Classes are groups of objects that share
    characteristics i.e. software blueprint
  • Object is the physical manifestation of a class
  • Each object is an instance of the class

22
Action Script
  • Script applied to an action
  • Basic structure of an action
  • whenSomethingHappens (input variables)
  • do stuff

23
ActionScript
  • Scripting language used in Flash to create
    advanced interactivity and animation
  • Allows the execution of different actions in a
    movie depending on what a user does or on what
    frame of the movie is being played
  • Similar structure and syntax to JavaScript
  • Example script

24
Creating ActionScript
  • Does not require
  • Detailed understanding of language
  • Hand-coding of scripts
  • Actions panel
  • Graphical interface to ActionScript
  • Build custom scripts using pre-written pieces of
    code
  • Define events, targets and actions
  • Scripts are validated automatically

25
Actionscript Fundamentals
  • ActionScript is a programming language
  • Subject to usual programming language constraints
  • Has its own syntax and structure

26
Some uses of ActionScript
  • Create multiplayer games
  • Create engaging, user-aware navigation
  • Send data to middleware, like PHP and Cold Fusion
  • Communicate with JavaScript

27
Benefits of using ActionScript
  • Allow for a more responsive Web site
  • Allows inclusion of dynamic data
  • Make your site more accessible to readers

28
ActionScript limitations
  • ActionScript can't talk directly to a database.
    Middleware like PHP, Cold Fusion, or ASP is
    needed to do this.
  • Can't use exception handling i.e. try, throw, or
    catch (Error handling in Javascript)
  • Exceptions provide error-handling capabilities
    for programs. An exception is an event that
  • occurs during the execution of a program that
  • disrupts the normal flow of instructions
  • This functionality can now be achieved using
    Macromedia Flash Remoting

29
ActionScript Functionality
  • Two ways to add ActionScript to Flash movie
  • Frame Actions code associated with particular
    keyframes of the movie
  • Custom classes code that resides in an external
    file
  • Flash component interactions create events and
    the associated actions are programmed as event
    handler functions
  • Event model used is DOM2, so event handlers are
    registered with addEventListener

30
Events
  • Events call an action
  • Dependent on user activity or autonomous
  • Single event can trigger multiple actions
  • Mouse events
  • Mouse movement, button clicks
  • Keyboard events
  • Keystrokes, text entry
  • Frame events
  • Occur automatically on entering frame
  • Attached to timeline of movie or movie-clip

31
Actions
  • Wide range of pre-defined actions
  • Movie control
  • Stop, play, go to frame, etc.
  • Movie Clip control
  • Set property, play/stop, etc.
  • Parameters can be customised
  • Actions can be
  • Performed on multiple targets
  • Conditional (If, then, else)

32
Targets
  • Target is object on which action is performed
  • Current movie
  • Movie-clip instances
  • External applications e.g. browsers
  • Defining targets
  • If no target defined action affects current
    object
  • Movie clip instances require unique name
  • Define path from current object to target

33
Learning Interactions
  • Templates for creating interactive assessment
  • Range of question types available
  • MCQ, drag-and-drop, hotspot, etc.
  • Parameters can be customised
  • Question, answers, feedback, etc.
  • Use Clip Parameters panel
  • Submissions can be tracked
  • Data sent to LMS
  • Quiz templates
  • Integrate a set of learning interactions

34
Action Buttons
  • Means of providing movie controls
  • e.g. Play, Stop, Rewind
  • Button states
  • Pre-defined keyframes in timeline
  • Can contain layers, animation, images, etc.
  • Built-in actions can be attached to buttons
  • Range of button sets provided by Macromedia

35
Object and Frame Actions
  • Two basic kinds of actions in Flash
  • Object actions
  • Frame actions

36
Object Actions - Movie Clips
  • Object actions are chunks of ActionScript code
    that are attached to an object
  • Usually an object is a symbol that is either a
    button or a movie clip
  • Graphic symbols dont have actions

37
Object and Frame Actions
38
Object Actions
  • An object action is associated with an instance
  • of a symbol, not with the symbol itself

39
Object Actions
  • Both shapes are instances of the same movie
  • clip symbol, but only one of them has an action
  • attached to it
  • The function is always attached to this object
  • instance, no matter where in the movie it appears
  • Object actions arent concerned with what frame
    the
  • movie is currently on (as long as the object
    actually
  • exists in the movie at that frame)

40
Event handlers
  • The function you saw was a onClipEvent
  • and is known as an event handler
  • An event is something that happens i.e. a
  • movie loads, user presses a mouse button
  • An event handler constantly looks for events
  • and lets ActionScript know when one of them occurs

41
Event handlers
42
Typical Event handler
  • OnmouseDown refers to what the mouse button is
    doing
  • If mouse button was pressed, then
    onClip-Event(mouseDown) is called, and everything
    inside the first set of curly braces is executed
  • OnmouseDown
  • startDrag(this)

43
Object Actions Drag fish
44
Methods
  • startDrag is what's called a method
  • A method does something
  • In this case drag what was clicked

45
Methods
  • A method is something an object can do or
    something
  • you can do to an object. For example, here are
    some
  • things methods can do
  • Stop a movie clip
  • Go to a certain frame and start playing there
  • See if a movie clip is over another movie clip
  • Hide the mouse cursor
  • Set the volume of a sound being played

46
Targets
  • Notice that we didn't use startDrag(), but used
    startDrag(this).
  • The startDrag method requires a target i.e., it
    needs to know what it should start dragging

47
this command
  • The easiest way to reference the current object
    is just to call it this
  • The other way to refer to the object is absolute
    i.e. startDrag(_root.drag_fish)
  • Where drag_fish is the name of the instance of
    the fish symbol
  • The _root part means "start looking from the top
    of the movie hierarchy"

48
Object actions onClipEvent
  • Object actions on a movie clip have to be inside
    of an
  • onClipEvent. Possible events are
  • load
  • unload
  • enterFrame
  • mouseMove
  • mouseDown
  • mouseUp
  • keyDown
  • keyUp

49
Object Actions Buttons
  • The only real difference between actions that
  • are attached to buttons instead of movie clips is
  • that the event handler for buttons is on
  • instead of onClipEvent
  • Otherwise, they're pretty much the same

50
Object Actions Buttons
  • The events for on are
  • press
  • release
  • releaseOutside
  • rollOver
  • rollOut
  • dragOver
  • dragOut
  • keyPress

51
Object Actions Buttons
52
Object Actions Buttons
53
Frame Actions
  • Frame actions are like object actions, except
    that the actions are associated with a certain
    spot in the timeline instead of an object
  • If a frame has some actions associated with it,
    those actions are carried when the playhead
    enters that frame

54
Frame Actions
55
Frame Actions
56
Frame Actions
  • Frame actions only allowed on a keyframe!!!
  • Hint Place all of your frame actions on a
  • separate layerit makes organization easier

57
Actionscript Syntax
  • ActionScript uses what is called dot syntax.
  • For example, if you have a movie clip called
  • red_shirt inside of the movie clip called
  • santa_claus, then one way to access that
  • object is
  • _root.santa_claus.red_shirt

58
Dot Syntax
  • To write paths actionscript uses what is called
    dot syntax.
  • E.g. to access the movie highlighted the path
    would be
  • _root.movieClip_one.clip_a.square1

59
Relative Absolute Paths
60
Root Properties
  • _root is the base of all Flash movies. If you
  • want to find out where red_shirt is on the stage,
  • you could use
  • xPosition _root.santa_claus.red_shirt._x
  • _x is a property that returns the horizontal
    position of the object

61
Root Properties
  • Its analogous to an absolute URL You start at
  • the top and specify your way down

62
Properties
  • A property is an attribute of an object. Movie
    clip
  • examples include
  • how wide it is (_width)
  • where it is on the stage (_x and _y)
  • what frame is currently being played
    (_currentframe)
  • how transparent it is (_alpha)
  • its name (_name)
  • whether it's visible or not (_visible)

63
Properties
  • Most properties can be read or altered. For
  • example, let's see how wide a movie clip called
  • clue is
  • _root.clue._width 110
  • _root.clue._width 40

64
underscore (_)
  • All movie clip properties start with an
  • underscore (_)
  • That's just how Flash is

65
Flash Overview
  • Interactive movies created with ActionScript
  • Simple interactivity
  • Does not require complete understanding of
    language
  • Build custom scripts from pre-written commands
  • Attach to buttons to provide user controls
  • Sophisticated interactivity
  • Customise elements provided by Macromedia
  • e.g. learning interactions, components

66
Flash Catalyst
67
Flash Catalyst
  • Adobe Flash Catalyst (formerly known by its
    codename Thermo) is a designers' tool for
    creating the user interface for Rich Internet
    Applications
  • With Flash Catalyst, user interface architects
    can create the user interface for Adobe
    Flex applications using Adobe graphic software.
    Then developers can use the result to build the
    rest of the application in Flex
  • https//www.adobe.com/cfusion/entitlement/index.cf
    m?returnurlhttp//tv.adobe.com/watch/flash-cataly
    st-cs5-feature-tour/top-5-flash-catalyst-cs5-featu
    res/eadobetvlocen

68
Features
  • Flash Catalyst can import Adobe Photoshop, Adobe
    Illustrator, or Adobe Fireworks files keeping all
    their features
  • Convert artwork into functional UI components
    (creating Flex component skins)
  • Create and edit behaviours (mouse event handling,
    etc.) without writing code
  • Create animated transitions
  • Return to Photoshop or Illustrator to modify the
    artwork, while preserving the behaviours,
    animation, etc. that were created in Catalyst
  • Create UIs to handle dynamic data without having
    access to the actual data source
  • Use design-time data placeholders when marking up
    an application, testing interactivity, and
    choreographing motion
  • Compatible with Flash Builder (formerly called
    "Flex Builder"), using the same project format

69
Flash Builder
  • Adobe Flash Builder (previously known as Adobe
    Flex Builder)3 is an integrated development
    environment (IDE) built on the Eclipse platform
    and speeds development of RIAs and cross-platform 
    desktop applications, particularly for the Adobe
    Flash platform
  • Adobe Flash Builder offers built-in code editors
    for MXML (Macromedia/Magic) and ActionScript and
    a WYSIWYG editor for modifying MXML applications
  • It includes an interactive debugger allowing
    developers to step through code execution while
    inspecting variables and watching expressions
  • It contains added support for performance
    analysis. The profiling view displays statistical
    information about memory use in addition to
    function call execution time
  • Prior to version 4, this product was known as
    Flex Builder. The name change is meant to signify
    its connection to other products in the Adobe
    Flash Platform and to create a clear distinction
    between the Flex SDK and the IDE

70
Flex SDK
  • Adobe Flex is a software development kit (SDK)
     for the development and deployment of
    cross-platform RIAs based on the Adobe
    Flash platform. Flex applications can be written
    using Adobe Flash Builder or by using the freely
    available Flex compiler from Adobe
  • In March 2004 Macromedia release included an SDK,
    an Integrated development environment (IDE), and
    a Java EE (Enterprise Edition) integration
    application known as Flex Data Services (now a
    separate product rebranded as LiveCycle Data
    Services
  • An alternative to Adobe LiveCycle Data Services
    is BlazeDS, an open-source project that started
    with code contributed in 2007 by Adobe
  • In February 2008, Adobe released the Flex 3 SDK
    under the open source Mozilla Public License and
    so Flex applications can be developed using any
    standard IDE, for example Eclipse

71
Eclipse
  • Eclipse is an open source community whose
    projects are focused on building an extensible
    development platform, runtimes and application
    frameworks for building, deploying and managing
    software across the entire software lifecycle
  • Eclipse is a multi-language software development
    environment comprising an integrated development
    environment (IDE) and an extensible plug-in
    system. It is written mostly in Java and can be
    used to develop applications in Java and, by
    means of various plug-ins, other programming
    languages including Ada, C, C, COBOL, Perl,
    PHP, Python, Ruby (including Ruby on Rails
    framework), Scala, Clojure, Scheme
  • The IDE is often called Eclipse ADT for Ada,
    Eclipse CDT for C/C, Eclipse JDT for Java, and
    Eclipse PDT for PHP

72
Projects
  • The Eclipse open source community has over 60
    open source projects. These projects can be
    conceptually organized into seven different
    "pillars" or categories
  • Enterprise Development
  • Embedded and Device Development
  • Rich Client Platform
  • Rich Internet Applications
  • Application Frameworks
  • Application Lifecycle Management (ALM)
  • Service Oriented Architecture (SOA)
  • http//www.eclipse.org/

73
Project examples
  • Core projects
  • Rich Client Platform is the core framework that
    all other Eclipse projects are built on
  • Java Development Tools (JDT) provides support for
    core Java SE includes a standalone fast
    incremental compiler
  • Tools projects
  • Plug-in Development Environment (PDE) provides
    tools to create, develop, test, debug, build and
    deploy Eclipse plug-ins, fragments and features
  • C/C Development Tools (CDT) adds support for
    C/C syntax highlighting, code formatting,
    debugger integration and project structures
  • Mylyn is a task-focused interface for Eclipse
    designed to reduce information overload and make
    multi-tasking easier.
  • Graphical Editing Framework (GEF) allows
    developers to build standalone graphical tools.
    Example use include circuit diagram design tools,
    activity diagram editors and WYSIWYG document
    editors
  • Buckminster adds support for Component Assemblies
  • WindowBuilder is a powerful and easy to use
    bi-directional Java GUI designer
  • Web projects
  • J2EE Standard Tools (JST) extends the core JDT to
    include support for Java EE projects - includes
    EJBs, JSPs and Servlets.
  • PHP Development Tools (PDT)
  • Web Standard Tools (WST) adds standards compliant
    web development tools. These tools include
    editors for XML, HTML and CSS

74
Examples (2)
  • Modelling projects
  • Eclipse Modeling Framework (EMF) a modeling
    framework and code generation facility for
    building tools and other applications based on a
    structured data model, from a model specification
    described in XMI
  • Graphical Modeling Framework (GMF) is a
    generative component and runtime infrastructure
    for developing graphical editors based on EMF and
    GEF
  • Technology projects
  • g-Eclipse which provides a middleware independent
    framework and exemplary implementations for
    users, developers, and administrators
    accessing Computing Grids
  • Subversive - SVN Team Provider (Subversive) is
    aimed at providing Subversion support
    in Eclipse similar to that previously provided
    for CVS
  • Other projects
  • Test and Performance Tools Platform (TPTP) which
    provides a platform that allows software
    developers to build test and performance tools,
    such as debuggers, profilers and benchmarking
    applications
  • Business Intelligence and Reporting Tools
    Project (BIRT), an Eclipse-based  open source
    reporting system for web applications, especially
    those based on Java EE
  • Data Tools Platform Project (DTP)
    provides relational database connectivity
    and SQL design tools.
  • Application Lifecycle Framework a closed project
    of the Eclipse Foundation

75
Ajax
76
Overview of Ajax History In the 1990s, most web
sites were based on complete HTML pages each
user action required that the page be re-loaded
from the server (or a new page loaded). This
process is inefficient, as reflected by the user
experience all page content disappears then
reappears, etc. Each time a page is reloaded due
to a partial change, all of the content must be
re-sent instead of only the changed information.
This can place additional load on the server and
use excessive bandwidth. Asynchronous loading of
content first became practical when Java
applets were introduced in the first version of
the Java language in 1995. These
allow compiled client-side code to load data
asynchronously from the web server after a web
page is loaded.  In 1996, Internet
Explorer introduced the iframe element to HTML,
which enabled asynchronous loading (appeared in
IE4 and Netscape 4) - An iframe element could be
made invisible and could be used to send
asynchronous requests In 1999, Microsoft created
the XMLHTTP ActiveX control in Internet Explorer
5, which was later adopted by Mozilla, Safari, Ope
ra and other browsers as the XMLHttpRequest JavaSc
ript object The utility of background HTTP
requests to the server and asynchronous web
technologies remained fairly obscure until it
started appearing in full scale online
applications such as Outlook Web
Access (2000) and Oddpost (2002)
77
  • Two events ignited widespread interest in Ajax
  • 1.  Google made a wide deployment of Ajax with
    Gmail (2004) and Google Maps (2005)
  • 2. The term Ajax was coined on February 18, 2005
    by Jesse James Garrett in an article
    entitled Ajax A New Approach to Web
    Applications.
  • Goal of Ajax is to provide Web-based applications
    with responsiveness approaching that of desk-top
    applications

78
Overview of Ajax (cont) Specific kind of Web
applications that benefit from Ajax are those
that have frequent interactions between the
client and the server Goals are achieved with
two different approaches 1. Client requests
are handled asynchronously 2. Only small parts
of the current document are updated Ajax does
not use any new programming languages or markup
languages - Client side JavaScript, XML,
XHTML, DOM, CSS - Server side any (PHP,
servlets, ASP.NET, etc.) Rather than the
original XMLHTML and XmlDocument objects, now the
XMLHttpRequest object is used Toolkits are now
often used to create Ajax applications, e.g.,
Prototype and Dojo (see later slides) Also,
frameworks, such as ASP.NET Ajax, JavaServer
Faces, and Rails
79
  • The Basics of Ajax
  • Described through a very simple application
  • The application Helps the user fill a form
  • The form gathers client information asks for the
    zip code before the names of the city and state
  • As soon as the zip code is entered, the
    application sends a request to the server, which
    looks up the city and state for the given zip
    code and returns them to the form
  • Uses JavaScript to put the city and state
    names in the form
  • Uses PHP on the server to look up the city and
    state
  • The form
  • Must reference the JavaScript code file in its
    head
  • Must register an event handler on the blur
    event of the zip code text box
  • Onblur getPlace(this.value)

80
  • The Basics of Ajax (cont)
  • Two functions are required by the application
  • 1. The blur handler
  • 2. A function to handle the response
  • The Request Phase (The blur handler)
  • The communication to the server for the
    asynchronous request must be made through the
    XMLHttpRequest object, so one must be created
  • var xhr new XMLHttpRequest()
  • When the server receives an asynchronous request,
    it sends a sequence of notices, called callbacks,
    to the browser (0, , 4)
  • Only the last one is of interest (4), which
    indicates that the response is complete, (the
    response function is what is called in the
    callbacks)
  • The response function must be registered on the
    onreadystatechange property of the XHR object
  • xhr.onreadystatechange receivePlace

81
The Request Phase (cont) Next, the handler must
call the open method of the XHR
object Parameters to open 1. HTTP
method, GET or POST, quoted 2. The URL
of the response document on the server
3. A Boolean literal to indicate whether the
request is to be asynchronous (true) or
synchronous (false) The parameter (the zip
code) must be attached to the URL (because GET
will be used) xhr.open("GET",
"getCityState.php?zip" zip, true)
(getCityState.php is the response document) The
request is sent with the send method
xhr.send(null)
82
The complete request handler function
  • function getPlace(zip)
  • var xhr new XMLHttpRequest ()
  • xhr.onreadystatechange receivePlace
  • xhr.open (GET, getCityState.php?zip zip,
    true)
  • xhr.send(null)

83
The Response Document
  • The response data is produced with a print
    statement
  • lt?php
  • // getCitystate.php
  • cityState array (81611 gt Aspen, Colorada,
  • 81411 gt
    Bedrock, Colorada,
  • 80908 gt Black
    Forest, Colorada
  • )
  • Header (Content-Type text/plain)
  • zip _GET zip
  • If (array_key_exists (zip,cityState))
  • print cityStatezip
  • else
  • print ,
  • ?gt

84
The Receiver Phase
  • A JavaScript function with no parameters
  • Fetch the server response (text), split it into
    its two parts (city and state), and set the
    corresponding text boxes to those values, (being
    able to access the XHR)
  • Actions of the receiver function
  • 1. Put all actions in the then clause of a
    selector that checks to see if readyState is 4
  • 2. Get the response value from the responseText
    property of the XHR object
  • 3. Split it into its two parts
  • 4. Set the values of the city and state text
    boxes

85
Complete request function getPlace
  • function getPlace(zip)
  • var xhr new XMLHttpRequest ( )
  • // Register the embedded receiver function as the
    handler xhr.onreadystatechange function ( )
  • If (xhr.readyState 4 xhr.status 200)
  • var result xhr.responseText
  • var place result.split ( , )
  • if (document.getElementById (city).value
    )
  • document.getElementById (city).value
    place0
  • if (document.getElementById (state).value
    )
  • document.getElementById (state).value
    place1
  • xhr.open(GET, getCityState.php?zip zip)
  • xhr.send(null)

86
Cross-Browser Support
  • What we have works with FX2 and IE7, but not
    earlier browsers such as IE5 and IE6 as these
    dont support the XHR object XMLHttpRequest
  • IE5 and IE6 support an ActiveXObject named
    Microsoft.XMLHTTP
  • xhr new ActiveXObject("Microsoft.XMLHTTP")
  • Function getPlace(zip)
  • //Get the object for all browsers except IE5 and
    IE6
  • If (window.XMLHttpRequest)
  • xhr new XMLHttpRequest ( )
  • //Otherwise get the object for IE5 and IE6
  • else
  • xhr newActiveXObject(Microsoft.XMLHTTP)

87
Return Document Forms
  • Several forms of data that can be returned from
    an Ajax request to the server
  • Plain text usually used for unstructured data
    such as XHTML, XML, JavaScript code, JavaScript
    Object Notation
  • For structured data use XHTML, XML, JavaScript
    Object Notation

88
  • 1. XHTML
  • Most common approach is to place an empty div
    element in the original document
  • The innerHTML property of the div element is
    assigned the new content
  • ltdiv id "replaceable_list"gt
  • lth2gt 2007 US Champion/Runnerup baseball lt/h2gt
  • ltulgt
  • ltligt Boston Red Socks lt/ligt
  • ltligt Colorado Rockies lt/ligt
  • lt/ulgt
  • lt/divgt
  • Now, if the user selects a different sport, say
    football, the XHTML response fragment could have
    the following
  • lth2gt 2007 US Champion/Runnerup football lt/h2gt
  • ltulgt
  • ltligt New York Giants lt/ligt ltligt New
    England Patriots lt/ligt

89
  • XHTML (cont)
  • Now, the returned fragment can be inserted in the
    div element with
  • var divDom document.getElementById(
  • "replaceable_list")
  • divDom.innerHTML xhr.responseText
  • The disadvantage of using XHTML for the return
    document is it works well only if markup is what
    is wanted
  • However, often times, it is data that is
    returned, in which case it must be parsed out of
    the XHTML

90
  • 2. XML
  • For the previous example, the following would
    be returned
  • ltheadergt 2007 US Champion/Runnerup football
  • lt/headergt
  • ltlist_itemgt New York Giants lt/list_itemgt
  • ltlist_itemgt New England Patriots lt/list_itemgt
  • Problem the XML returned must also be parsed,
    with two approaches to do so
  • A. Use the DOM binding parsing methods
  • - Two disadvantages
  • i. Writing the parsing code is
    tedious
  • ii. Support for DOM parsing
    methods is a bit inconsistent over various
    browsers
  • B. Use XSLT style sheets

91
2. XML - XSLT stylesheet example ltxslstyleshee
t version "1.0" xmlnsxsl
"http//www.w3.org/1999/XSL/Transform" xmlns
"http//www.w3.org/1999/xhtml" gt ltxsltemplate
match "/"gt lth2gt ltxslvalue-of select
"header" /gt lt/h2gt ltbr /gt ltbr /gt ltulgt
ltxslfor-each select "list_item"gt ltligt
ltxslvalue-of select "list_item"/gt
ltbr /gt lt/ligt lt/xslfor-eachgt
lt/ulgt lt/xsltemplategt lt/xslstylesheetgt
92
  • 3. JavaScript Object Notation (JSON)
  • Part of the JavaScript standard, 3rd edition
  • A method of representing objects as strings,
    using two structures
  • A. Collections of name/value pairs
  • B. Arrays of values
  • "employees"
  • "name" "Dew, Dawn", "address"
  • "1222 Wet Lane",
  • "name" "Do, Dick", "address"
  • "332 Doer Road",
  • "name" "Deau, Donna", "address"
  • "222 Donne Street"

93
3. JavaScript Object Notation (JSON) (cont) The
object could be obtained by running eval on the
response string This is dangerous, because the
response string could have malicious code, it is
safer to get and use a JSON parser
var response xhr.responseText var
myObj JSON.parse(response) JSON has at least
three advantages over XML 1. JSON
representations are smaller 2. parse is
much faster than manual parsing or using XSLT
3. parse is much easier than manual parsing or
using XSLT XML is better if the returned data is
going to be integrated with the original document
use XSLT
94
3. JavaScript Object Notation (JSON)
(cont) Example return document
"top_two" "sport" "football",
"team" "New York
Giants", "sport" "football", "team"
"New England Patriots",
The processing to put it in the XHTML
document var myObj JSON.parse(response) docum
ent.write("lth2gt 2007 US Champion/Runnerup"
myObj.top_two0.sport "lt/h2gt") document.writ
e("ltulgt ltligt" myObj.top_two0.team
"lt/ligt") document.write("ltligt"
myObj.top_two1.team "lt/ligtlt/ulgt")
95
Ajax Toolkits There are many toolkits to help
build Ajax applications, for both server-side and
client-side Client-side toolkits 1.
Dojo A free JavaScript library of modules, for
Ajax and other parts of Web site software which
provides commonly needed code and hides the
differences among browsers An example ordering
a shirt on-line After the user selects a size,
present the user with the colors in that size
that are now in stock Use Ajax to get the colors
for the chosen size The original document is for
one particular style of shirt, including a menu
for sizes and an empty menu for colors
96
1. Dojo (cont) The required JavaScript must
define two functions A. buildMenu the callback
function to build the menu of colors - Get the
DOM address of the empty select - If it is not
the first request, set options property to
zero - Split the returned value (a string of
colors separated by commas and spaces) - Build
the Options of the menu and add them to the menu
with add - The second parameter to add is
browser dependent for IE, it is -1 for others,
it is null B. getColors a wrapper function
that calls bind to create the Ajax request
97
  • 2. Prototype
  • A toolkit that extends JavaScript and provides
    tools for Ajax applications
  • Includes a large number of functions and
    abbreviations of commonly needed JavaScript code
  • ("name") is an abbreviation for
  • document.getElementById("name")
  • document.getElementById("name"). Value
    Freddie
  • ("name"). Value Freddie
  • In Prototype, all of the Ajax functionality is
    encapsulated in the Ajax object. A request is
    created by creating an object of Ajax.Request
    type, sending the parameters to the constructor
  • The first parameter is the URL of the server
  • The second parameter is a literal object with
    the other required information
  • - method "get" or "post"

98
Code example
  • new Ajax.request(getCityState.php,
  • Method get,
  • Parameters zip zip
  • onSuccess function (request)
  • var place request.responseText.split (
    , )
  • (city).value place0
  • (state).value place1
  • onFailure function (request)
  • alert (Error request failed)
  • )

99
Security and Ajax Issues 1. In many cases,
Ajax developers put security code in the client
code, but it also must be included in the server
code, because intruders can change the code on
the client 2. Non-Ajax applications often
have just one or only a few server-side sources
of responses, but Ajax applications often have
many server-side programs that produce small
amounts of data. This increases the attack
surface of the whole application. 3.
Cross-site scripting servers providing
JavaScript code as an Ajax response. Such code
could be modified by an intruder before it is run
on the client All such code must be scanned
before it is interpreted Intruder code could
also come to the client from text boxes used to
collect return data It could include script
tags with malicious code
Write a Comment
User Comments (0)
About PowerShow.com