- Forward


ECMAScript/JavaScript Communications
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Overview
Back SMYC Forward
  • The Application-Layer Protocol:
    • Hypertext Transfer Protocol
  • The Important Classes:
    • XMLHttpRequest
    • XMLDOM
  • The Process:
    • Create an XMLHttpRequest object
    • Call the open() method
    • Call the send() method
    • Either synchronously or asynchronoulsy, wait for the response
    • Construct an XMLDOM object from the response
    • Work with the XMLDOM object
Some Details
Back SMYC Forward
  • Parameters of the open() Method:
    • The request type ("GET" or "POST")
    • The URL
    • false for synchronous, true for asynchronous
  • Parameters of the send() Method:
    • The optional parameter can be used to include ampersand-delimited name=value lines in a POST request
  • Another Useful Method:
    • The setRequestHeader(header,value) method can be used to add HTTP headers to the request
Some Details (cont.)
Back SMYC Forward
  • After the Call Returns:
    • The XMLHttpRequest object will contain the response
  • Accessing the Response:
    • An XML response will be in the responseXML attribute
    • A text response will be in the responseText attribute
  • For Asynchronous Requests:
    • The XMLHttpRequest object's onreadstatechange attribute must contain the function to call
A Simple Example
Back SMYC Forward

A Weight Retriever Click here for a demonstration.

ecmascriptexamples/http/alice.xml
 
ecmascriptexamples/http/weight-retriever.html
 
ecmascriptexamples/http/weight-retriever.js
 
A More Interesting Example
Back SMYC Forward
  • Purpose:
    • A generic slideshow "web app" that retrieves the slides
  • Some Obervations:
    • An XML file contains the slides
    • The easiest way to structure the slides is to use HTML
  • The Implication:
    • To make sure the HTML in the HTML file isn't parsed, we need to make it "data"
A More Interesting Example (cont.)
Back SMYC Forward

A Slideshow App Click here for a demonstration.

ecmascriptexamples/http/slideshow.html
 
ecmascriptexamples/http/slideshow.css
 
ecmascriptexamples/http/slides.xml
 
ecmascriptexamples/http/SlidePresenter.js
 
ecmascriptexamples/http/slideshow.js
 
A More Interesting Example (cont.)
Back SMYC Forward
  • Suppose:
    • You want to include the name of the file containing the slides in the query string of the URL
  • Getting the URL:
    • document.URL (part of the DOM)
    • window.location (non-standard but supported)
  • Working with the URL:
    • The global decodeURI() and encodeURI() functions can be used to convert from/to the standard encoding (e.g., no spaces)
    • Strings have lastIndexOf() and split() methods that can be used to tokenize the URL
There's Always More to Learn
Back -