javascript & ajax basics
TRANSCRIPT
Javascript + Ajax Basics
Richard PaulKiwiplan NZ Ltd30th Jan 2009
Javascript the Language
JavaScript is a scripting language widely used for client-side web development. ... It is a dynamic, weakly typed, prototype-based language with first-class functions. -- http://en.wikipedia.org/wiki/Javascript
Declaring Variables
var greeting = 'Hello'var greeting = 'Hello'; // Semicolons are optionalvar greeting = "Hello" // Single & double quotes are // equivalent
var date = new Date() // Arrayvar pets = ['cat', 'dog', 'fish'] // Map var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'}
// Globally accessiblegreeting = 'Hello World'
Functions & Function Scope
// Legal function funA(num) { if (i % 2 == 0) { var x = 10 } else { var x = 20 } x *= 2 return x}
// This will reassign x to 2, not shadow x (as seen in Java etc).function funB(num) { var x = 1 if (num < 10) { var x = 2 }}
Javascript supports function scope, but not block scope.(Javascript 1.7 introduced 'let' for block scope, not supported in IE)
Functions as objects
// Define a function called funAfunction funA() {}
// Define a function, assign to variable funBvar funB = function() {} // Scoped functions function init() { var funC = function() { alert('hi') } funC() // OK}init() funC() // => ReferenceError: funC is not defined
Javascript conditionals
// Javascript truth // undefined is falsevar xif (x) { // Won't reach here} // empty string is falsevar x = ''if (x) { // Won't reach here}
// Ternery operator function doubleOrNothing(x) { return x % 2 == 0 ? x*=2 : 0}doubleOrNothing(2) // => 4doubleOrNothing(3) // => 0
// Default valuesfunction X(num) { this.num = num || 0}
Optional function arguments
// Adds x, y and an optional z argumentfunction adder(x, y, z) { var value = x + y if (z) { value += z } return value}
adder() // => undefined + undefined = NaNadder(2) // => 2 + undefined = NaNadder(2, 3) // => 5adder(2, 3, 4) // => 9adder(2, 3, 4, 5) // => 9, last argument ignored
A better adder(the arguments keyword)
function adder() { var total = 0 for (var i = 0; i < arguments.length; i++) { total += arguments[i] } return total} adder() // => 0 adder(1) // => 1adder(1, 2) // => 3
Closures
Closures wrap a function, and its environment (variables) to allow it to be executed later. function init() { var num = 10 function addNum(myNum) { return num + myNum } return addNum }
var myAdder = init() // Creates a closuremyAdder(1) // => 11
Defining Objectsfunction Counter(num) { this.num = num || 0 this.increment = function() { this.num++ } this.decrement = function() { this.num-- } this.add = function(otherNum) { this.num += otherNum }} While this is simple, it is inefficient as the functions are defined every time a Counter object is created.-- https://developer.mozilla.org/.../ClosurePerformance
Exceptions
openMyFile()try { writeMyFile(theData) // This may throw a error} catch(e) { handleError(e) // Handle any errors} finally { closeMyFile() // Always close the resource}
-- https://developer.mozilla.org/.../try...catch_Statement
Regex
// Literal var regex = /\d+/// Object var regex = new Regex('\\d+')
// Extract hash from a URL// e.g. http://example.com/#example2 function extractHash(url) { var matches = url.match(/#.*/) if (matches) { return matches[0] } return '' // Default to empty string if no hash }
extractHash('http://example.com/#example2') // => #example2
AJAX - Asynchronous Javascript and XML
AJAX is the general term relating to web development techniques used to update pages dynamically.
Is a misnomer as requests aren't required to be asynchronous or return XML (any text can be returned).
XmlHttpRequest is the underlying object used to make requests to a server without requiring a page reload.
AJAX - GET
Retrieve information from a server without a page load. var request = new XMLHttpRequest()request.open('GET', 'service/time', true)request.onreadystatechange = function () { if (request.readyState == 4) { // 4 = loaded if (request.status == 200) { // 200 = success alert(request.responseText) // or responseXML } else { alert('Error loading page: ' + request.status) } }}request.send(null)
AJAX - POST
Send information to a server without a page load. var url = "theUrl"var params = "name=Groovy&speaker=Kugan"http.open("POST", url, true)
http.setRequestHeader("Content-type", "application/x- www-form-urlencoded")http.setRequestHeader("Content-length", params.length)http.setRequestHeader("Connection", "close")
http.onreadystatechange = function() { // Do something with the response}http.send(params)
DOM ManipulationDocument Object Model - The object representation of an XML page (the structure of a web page).
document.getElementById('myTextbox').value = 'new value' var content = document.getElementById('myContent')content.innerHTML = 'new content'
// Get elements for a certain tag, change link name.var links = document.getElementsByTagName('a')for (var i = 0; i < links.length; i++) { links[i].innerHTML += ' :-)' // Appends a smiley}
// Add element to pagevar div = document.createElement('div')div.innerHTML = 'This is some content'document.body.appendChild(div)
Javascript isn't just for web browsers
While Javascript is most widly used for client side scipting in a browser, it is a fully fledged language and can be used anywhere.
Rhino - Open source Javascript engine. AppJet - 'Instant web programming', server side javascriptJaxer - Server side javascript
Useful Resources
Javascript Console (live demo)http://nzrichardp:9090/AjaxServer/ (session 1) http://nzrichardp:9091/AjaxServer/ (session 2)
Live Demo source (grails app, Kiwiplan CVS)Install Java + GrailsLaunch with 'grails run-app'
Mozilla Javascript ReferenceW3 Spec for XmlHttpRequest Learning Advanced JavascriptJavascript Closures
Mozilla DeveloperStack Overflow