Javascript & Ajax Basics

4,061 views
3,914 views

Published on

Published in: Technology
1 Comment
5 Likes
Statistics
Notes
  • A live javascript console is also available to accompany these slides at: http://www.rapaul.com/2009/02/02/javascript-ajax-basics-slides/
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
4,061
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
206
Comments
1
Likes
5
Embeds 0
No embeds

No notes for slide

Javascript & Ajax Basics

  1. 1. Javascript + Ajax Basics Richard Paul Kiwiplan NZ Ltd 30th Jan 2009
  2. 2. 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
  3. 3. Declaring Variables var greeting = 'Hello' var greeting = 'Hello'; // Semicolons are optional var greeting = quot;Helloquot; // Single & double quotes are // equivalent var date = new Date() // Array var pets = ['cat', 'dog', 'fish'] // Map var petNames = {cat:'Garfield', dog:'Snoopy', fish:'Nemo'} // Globally accessible greeting = 'Hello World'
  4. 4. Functions & Function Scope Javascript supports function scope, but not block scope. (Javascript 1.7 introduced 'let' for block scope, not supported in IE) // This will reassign x to 2, not // Legal shadow x (as seen in Java etc). function funA(num) { function funB(num) { if (i % 2 == 0) { var x = 1 var x = 10 if (num < 10) { } else { var x = 2 var x = 20 } } } x *= 2 return x }
  5. 5. Functions as objects // Define a function called funA function funA() {} // Define a function, assign to variable funB var funB = function() {} // Scoped functions function init() { var funC = function() { alert('hi') } funC() // OK } init() funC() // => ReferenceError: funC is not defined
  6. 6. Javascript conditionals // Ternery operator // Javascript truth function doubleOrNothing(x) { // undefined is false return x % 2 == 0 ? x*=2 : 0 var x } if (x) { doubleOrNothing(2) // => 4 // Won't reach here doubleOrNothing(3) // => 0 } // empty string is false // Default values var x = '' function X(num) { if (x) { this.num = num || 0 // Won't reach here } }
  7. 7. Optional function arguments // Adds x, y and an optional z argument function adder(x, y, z) { var value = x + y if (z) { value += z } return value } adder() // => undefined + undefined = NaN adder(2) // => 2 + undefined = NaN adder(2, 3) // => 5 adder(2, 3, 4) // => 9 adder(2, 3, 4, 5) // => 9, last argument ignored
  8. 8. 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) // => 1 adder(1, 2) // => 3
  9. 9. 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 closure myAdder(1) // => 11
  10. 10. Defining Objects function 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
  11. 11. 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
  12. 12. 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
  13. 13. 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.
  14. 14. 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)
  15. 15. AJAX - POST Send information to a server without a page load. var url = quot;theUrlquot; var params = quot;name=Groovy&speaker=Kuganquot; http.open(quot;POSTquot;, url, true) http.setRequestHeader(quot;Content-typequot;, quot;application/x- www-form-urlencodedquot;) http.setRequestHeader(quot;Content-lengthquot;, params.length) http.setRequestHeader(quot;Connectionquot;, quot;closequot;) http.onreadystatechange = function() { // Do something with the response } http.send(params)
  16. 16. DOM Manipulation Document 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 page var div = document.createElement('div') div.innerHTML = 'This is some content' document.body.appendChild(div)
  17. 17. 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 javascript Jaxer - Server side javascript
  18. 18. 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 + Grails Launch with 'grails run-app' Mozilla Javascript Reference W3 Spec for XmlHttpRequest Learning Advanced Javascript Javascript Closures Mozilla Developer Stack Overflow

×