Scripting with Server Access

Mobile Application Design and Development [./]
Spring 2010 — INFO 152 (CCN 42504)

Erik Wilde, UC Berkeley School of Information
2010-02-17

Creative Commons License [http://creativecommons.org/licenses/by/3.0/]

This work is licensed under a CC
Attribution 3.0 Unported License
[http://creativecommons.org/licenses/by/3.0/]

Contents Erik Wilde: Scripting with Server Access

Contents

Erik Wilde: Scripting with Server Access

(2) Abstract

Scripting is used on the majority of today's modern Web sites. Scripting can be used to improve the usability and accessibility of a Web site (for example for validating form data on the client side), it can vastly improve the user experience with new interface design (the smooth scrolling of Google Maps vs. older click to scroll map services), or it can be used to implement behavior that would be impossible without scripting (for example the online applications of Google Docs). Asynchronous JavaScript and XML (Ajax) takes Dynamic HTML (DHTML) to the next level by allowing server access from within scripting code. This is accomplished by using a standardized API for client/server communications, the XMLHttpRequest object. This objects allows using HTTP connections from within scripting code, and thereby allows scripting code to dynamically reload data from a server in response to user interactions.



Current Events

Outline (Current Events)

  1. Current Events [2]
  2. Web App Development [2]
  3. Ajax Mechanics [8]
  4. Ajax Practicalities [2]
  5. JavaScript Frameworks [7]
Current Events Erik Wilde: Scripting with Server Access

(4) MeeGo = Maemo + Moblin

meego.jpg

Current Events Erik Wilde: Scripting with Server Access

(5) RIM goes WebKit

torch-acid.jpg

Web App Development

Outline (Web App Development)

  1. Current Events [2]
  2. Web App Development [2]
  3. Ajax Mechanics [8]
  4. Ajax Practicalities [2]
  5. JavaScript Frameworks [7]
Web App Development Erik Wilde: Scripting with Server Access

(7) Scripting on the Web



Web App Development Erik Wilde: Scripting with Server Access

(8) The Joys of Web Design

Time Breakdown of Modern Web Design

Ajax Mechanics

Outline (Ajax Mechanics)

  1. Current Events [2]
  2. Web App Development [2]
  3. Ajax Mechanics [8]
  4. Ajax Practicalities [2]
  5. JavaScript Frameworks [7]
Ajax Mechanics Erik Wilde: Scripting with Server Access

(10) Misleading Name



Ajax Mechanics Erik Wilde: Scripting with Server Access

(11) Minimal XMLHttpRequest Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <script type="text/javascript">
   var http = new XMLHttpRequest();
   http.open("GET", "helloworld.xml", true);
   http.onreadystatechange = function() {
    if ( this.readyState == 4 && this.status == 200 ) {
     var xml = http.responseXML.documentElement;
     var helloworld = document.createTextNode(' ' + xml.firstChild.nodeValue);
     document.getElementById('demo').appendChild(helloworld);
    }
   }
   http.send();
  </script>
 </head>
 <body>
  <p id="demo">Ajax-based</p>
 </body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<xml>"Hello World!"</xml>


Ajax Mechanics Erik Wilde: Scripting with Server Access

(12) HTTP Interactions



Ajax Mechanics Erik Wilde: Scripting with Server Access

(13) Handling XMLHttpRequest Responses



Ajax Mechanics Erik Wilde: Scripting with Server Access

(14) Inspecting XMLHttpRequest Responses

// The following script:
var client = new XMLHttpRequest();
client.open("GET", "test.txt", true);
client.send();
client.onreadystatechange = function() {
	if(this.readyState == 2) {
		print(client.getResponseHeader("Content-Type"));
	}
}

// ...should output something similar to the following text:
Content-Type: text/plain; charset=utf-8


Ajax Mechanics Erik Wilde: Scripting with Server Access

(15) Requesting XMLHttpRequest Responses

// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'ajax-data');
client.setRequestHeader('Accept', 'application/json;q=1.0, application/xml;q=0.8');
client.send();

// ... results in the following header being sent:
...
Accept: application/json;q=1.0, application/xml;q=0.8
...


Ajax Mechanics Erik Wilde: Scripting with Server Access

(16) Using XML Structures

var xml_menu = '<menu id="file" value="File">' + '\n' +
'<popup>' + '\n' +
'<menuitem value="New" onclick="CreateNewDoc()" />' + '\n' +
'<menuitem value="Open" onclick="OpenDoc()" />' + '\n' +
'<menuitem value="Close" onclick="CloseDoc()" />' + '\n' +
'</popup>' + '\n' +
'</menu>';

WhatHappensWhenYouClick_Xml(xml_menu);

function WhatHappensWhenYouClick_Xml(data){
  var x = new ActiveXObject( "Microsoft.XMLDOM" );
  x.loadXML(data);
  WScript.Echo("When you click the " + x.documentElement.getAttribute("value") + " menu, you get the following options");
  var nodes = x.documentElement.selectNodes("//menuitem");
  for(var i = 0; i < nodes.length; i++){
   WScript.Echo((i + 1) + "." + nodes[i].getAttribute("value") + " aka " + nodes[i].getAttribute("onclick"));
  }
}


Ajax Mechanics Erik Wilde: Scripting with Server Access

(17) Using JSON Structures

var json_menu = '{"menu": {' + '\n' +
'"id": "file",' + '\n' +
'"value": "File",' + '\n' +
'"popup": {' + '\n' +
'"menuitem": [' + '\n' +
'{"value": "New", "onclick": "CreateNewDoc()"},' + '\n' +
'{"value": "Open", "onclick": "OpenDoc()"},' + '\n' +
'{"value": "Close", "onclick": "CloseDoc()"}' + '\n' +
']' + '\n' +
'}' + '\n' +
'}}';

WhatHappensWhenYouClick_Json(json_menu);

function WhatHappensWhenYouClick_Json(data){
  var j = eval("(" + data + ")");
  WScript.Echo("When you click the " + j.menu.value + " menu, you get the following options");
  for(var i = 0; i < j.menu.popup.menuitem.length; i++){
   WScript.Echo((i + 1) + "." + j.menu.popup.menuitem[i].value + " aka " + j.menu.popup.menuitem[i].onclick);
  }
}


Ajax Practicalities

Outline (Ajax Practicalities)

  1. Current Events [2]
  2. Web App Development [2]
  3. Ajax Mechanics [8]
  4. Ajax Practicalities [2]
  5. JavaScript Frameworks [7]
Ajax Practicalities Erik Wilde: Scripting with Server Access

(19) Same-Origin Policy



Ajax Practicalities Erik Wilde: Scripting with Server Access

(20) XMLHttpRequest Implementations



JavaScript Frameworks

Outline (JavaScript Frameworks)

  1. Current Events [2]
  2. Web App Development [2]
  3. Ajax Mechanics [8]
  4. Ajax Practicalities [2]
  5. JavaScript Frameworks [7]
JavaScript Frameworks Erik Wilde: Scripting with Server Access

(22) Abstraction and Reality



JavaScript Frameworks Erik Wilde: Scripting with Server Access

(23) XMLHttpRequest in jQuery (Setup)

 ajaxSettings: {
  url: location.href,
  global: true,
  type: "GET",
  contentType: "application/x-www-form-urlencoded",
  processData: true,
  async: true,
  /*
  timeout: 0,
  data: null,
  username: null,
  password: null,
  traditional: false,
  */
  // Create the request object; Microsoft failed to properly
  // implement the XMLHttpRequest in IE7 (can't request local files),
  // so we use the ActiveXObject when it is available
  // This function can be overriden by calling jQuery.ajaxSetup
  xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
   function() {
    return new window.XMLHttpRequest();
   } :
   function() {
    try {
     return new window.ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {}
   },
  accepts: {
   xml: "application/xml, text/xml",
   html: "text/html",
   script: "text/javascript, application/javascript",
   json: "application/json, text/javascript",
   text: "text/plain",
   _default: "*/*"
  }
 },


JavaScript Frameworks Erik Wilde: Scripting with Server Access

(24) XMLHttpRequest in jQuery (Interface)

 get: function( url, data, callback, type ) {
  // shift arguments if data argument was omited
  if ( jQuery.isFunction( data ) ) {
   type = type || callback;
   callback = data;
   data = null;
  }

  return jQuery.ajax({
   type: "GET",
   url: url,
   data: data,
   success: callback,
   dataType: type
  });
 },

 getScript: function( url, callback ) {
  return jQuery.get(url, null, callback, "script");
 },

 getJSON: function( url, data, callback ) {
  return jQuery.get(url, data, callback, "json");
 },


JavaScript Frameworks Erik Wilde: Scripting with Server Access

(25) XMLHttpRequest in jQuery (Core)

 ajax: function( origSettings ) {
  var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
  
  var jsonp, status, data,
   callbackContext = origSettings && origSettings.context || s,
   type = s.type.toUpperCase();

  // convert data if not already a string
  if ( s.data && s.processData && typeof s.data !== "string" ) {
   s.data = jQuery.param( s.data, s.traditional );
  }

  // Handle JSONP Parameter Callbacks
  if ( s.dataType === "jsonp" ) {
   if ( type === "GET" ) {
    if ( !jsre.test( s.url ) ) {
     s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
    }
   } else if ( !s.data || !jsre.test(s.data) ) {
    s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
   }
   s.dataType = "json";
  }

  // Build temporary JSONP function
  if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
   jsonp = s.jsonpCallback || ("jsonp" + jsc++);

   // Replace the =? sequence both in the query string and the data
   if ( s.data ) {
    s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
   }

   s.url = s.url.replace(jsre, "=" + jsonp + "$1");

   // We need to make sure
   // that a JSONP style response is executed properly
   s.dataType = "script";

   // Handle JSONP-style loading
   window[ jsonp ] = window[ jsonp ] || function( tmp ) {
    data = tmp;
    success();
    complete();
    // Garbage collect
    window[ jsonp ] = undefined;

    try {
     delete window[ jsonp ];
    } catch(e) {}

    if ( head ) {
     head.removeChild( script );
    }
   };
  }


JavaScript Frameworks Erik Wilde: Scripting with Server Access

(26) Web Design Patterns



JavaScript Frameworks Erik Wilde: Scripting with Server Access

(27) Popular Frameworks



JavaScript Frameworks Erik Wilde: Scripting with Server Access

(28) Important Framework Questions



Erik Wilde: Scripting with Server Access

(29) Conclusions



2010-02-17 Mobile Application Design and Development [./]
Spring 2010 — INFO 152 (CCN 42504)