advertisement

Javascript & Ajax Basics

33 %
67 %
advertisement
Information about Javascript & Ajax Basics
Technology

Published on February 2, 2009

Author: rapaul

Source: slideshare.net

advertisement

Javascript + Ajax Basics Richard Paul Kiwiplan NZ Ltd 30th 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 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'

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 }

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

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 } }

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

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

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

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

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 = 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)

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)

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

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

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

JavaScript Tutorial - W3Schools

JavaScript is the programming language of HTML and the Web. Programming makes computers do what you want them to do. JavaScript is easy to learn. This ...
Read more

AJAX Introduction - w3schools.com

AJAX is a developer's dream, because you can: Update a web page without reloading the page Request data from a server - after the page has loaded Receive ...
Read more

JavaScript.com

Learn JavaScript and stay connected with the latest news created and curated by the JavaScript community.
Read more

Getting Started - Ajax | MDN

This article guides you through the AJAX basics and ... Ajax; Getting Started; ... you just need to tell the HTTP request object which JavaScript ...
Read more

AJAX Basics Course - Start Learning at Treehouse for Free

AJAX is an important front-end web technology that lets JavaScript communicate with a web server. It lets you load new content without leaving the current ...
Read more

Introducing AJAX | AJAX Basics | Treehouse

Introducing Asynchronous JavaScript and XML, or AJAX. How it works, who uses it and why you should learn it.
Read more

Coaching: Ajax, Basics - Springest

Inhalte Einführung in Ajax JavaScript-Crashkurs DOM und Events Zusammenspiel mit CSS und XML XML Http Request Frameworks Libraries Methode Erleben Sie ...
Read more

jQuery.ajax() | jQuery API Documentation

jQuery: The Write Less, Do More, JavaScript Library. jQuery; ... As of jQuery 1.5, jQuery's Ajax implementation includes prefilters, ... Basics; Custom ...
Read more

Ajax | jQuery Learning Center

Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered ...
Read more

javascriptbasics - home

Die ersten Browser und Javascript wurden vor mehr als 20 Jahren in den USA entwickelt, ... Ajax: Eine kleine Einführung - siehe z.B.
Read more