Download presentation
Presentation is loading. Please wait.
Published byAugustus Riley Modified over 9 years ago
1
Chapter 6 JavaScript and AJAX
2
Objectives Explain the purpose and history of JavaScript Describe JavaScript features Explain the event-driven nature of JavaScript and name DOM events Explain how JavaScript dialog boxes work Use JavaScript to validate forms Explain Ajax operation, synchronous and asynchronous Use Ajax for simple data lookups Explain Ajax cost and benefits
3
JavaScript History Originally "LiveScript" –Renamed for marketing purposes Not directly related to Java International standard as ECMAScript –European Computer Manufacturers Assoc. JavaScript 1.8 similar to ECMAScript 3 Similar JScript developed by Microsoft
4
JavaScript Features (1/2) A scripting language –informal syntax, minimal coding Dynamic variable typing –boolean, number, string, function, object –implicit type conversions –potential problem w.r.t. correctness, security First-class functions –Functions can be passed by variable
5
JavaScript Features (2/2) Event-driven –Programs respond to user interface actions (mouse movement, click, keystroke, etc.) Server-Side or Client-Side –JavaScript can be used on either platform –Most commonly used client-side for user interface enhancement Client-Side functionality –JavaScript functions can add, change, or delete any HTML element –Changes are dynamically re-displayed
6
Adding JavaScript to HTML JavaScript code can be placed anywhere in an HTML document Typically placed at the end of Delimited by … JavaScript Demo function sayHello() { alert("Hello!"; }
7
Invoking JavaScript Code JavaScript functions can be tied to DOM events on individual HTML elements –using onX="function()", where 'X' is an event function color(button, color) { button.style.background=color } <input type="button" value="Click Me" onmouseover="color(this, #FF0000)" onmouseout="color(this, #E0E0E0)" /> red gray Click Me self-reference
8
DOM Events User-Initiated click dlbclick keydown keyup keypress mouseover mouseout mousedown mouseup mousemove change resize scroll select blur focus reset submit Browser-Initiated load unload error abort
9
Dialog Boxes Dialog boxes can be used to –inform the user of errors or events –confirm actions initiated by the user
10
User Action Confirmation Dialog function confirmDelete() { var answer = confirm("Are you sure you want" + "to delete this player?"); return answer }... if the user clicks "Cancel", the form will NOT be submitted
11
Form Validation function validate() { if (document.getElementById("name").value.length == 0) { alert("Please complete the required fields\n" + "and resubmit."); return false; } return true; } Add Player: <form id="form1" action="addplayer" onsubmit="return validate()" > Name:... if the procedure returns false, the form will NOT be submitted
12
HTML Manipulation function validate() { if (document.getElementById("name").value.length == 0) { alert("Please complete the required fields\n" + "and resubmit."); document.getElementById("nameflag").innerHTML = "* " return false; } document.getElementById("nameflag").innerHTML = "" return true; } Add Player: <form id="form1" action="addplayer" onsubmit="return validate()" > Name:...
13
Ajax Ajax allows a JavaScript procedure to execute an HTTP transaction in the background Ajax can be used to fetch information, images, etc., or to pass information to the server in order to enhance the user experience of a web page
14
Ajax
15
Ajax Setup An XMLHttpRequest object is created to channel HTTP transactions window.onload = createXMLHttpRequest; function createXMLHttpRequest() { try { // for Firefox, IE7, Opera xmlreq = new XMLHttpRequest(); } catch (e) { try { // for IE6 xmlreq = new ActiveXObject('MSXML2.XMLHTTP.5.0'); } catch (e) { xmlreq = null; }...
16
Synchronous Ajax Ajax can be used in simple "synchronous" mode, in which the user interface is blocked (unusable) while a transaction completes var url = "...server URL..." xmlreq.open('GET', url, false); xmlreq.send(null); var response = xmlreq.responseText; Send HTTP request Receive HTTP response
17
Asynchronous Ajax With asynchronous Ajax, the user interface continues to operate while the client listens for a response xmlreq.open('GET', url, true); xmlreq.onreadystatechange = function() { if (xmlreq.readyState == 4) if (xmlreq.status == 200) var response = xmlreq.responseText; else alert('Ajax failed; status: ' + xmlreq.status); } xmlreq.send(null);
18
Ajax ReadyState Values Ready StateSignificance 0 UninitializedRequest not yet opened 1 LoadingNot yet sent 2 LoadedSent; no information available 3 InteractivePartial response received 4 CompletedResponse complete
19
Ajax Example (1/2) function checkNumber(custNr) { if (custNr.length < 9) return var url = "getname?custnr=" + custNr xmlreq.open('GET', url, true) xmlreq.onreadystatechange = function() { if (xmlreq.readyState == 4) if (xmlreq.status == 200) document.getElementById('name').innerHTML = xmlreq.responseText } xmlreq.send(null) } <input type="text" id="custnr" onkeyup="checkNumber(this.value)" />
20
Ajax Example (2/2) import java.io.*; import javax.servlet.http.*; public class NameLookup extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { String custNr = req.getParameter("custnr"); String custName =... lookup customer name... ; PrintWriter out = res.getWriter(); res.setContentType("text/plain"); out.write(custName); out.close(); }
21
Ajax Benefits and Costs Benefits –Rich and responsive user interfaces –Novel web applications Costs –Increased network and server load –Increased complexity of design and coding
22
Review JavaScript purpose and history JavaScript and the DOM event model JavaScript dialog boxes JavaScript and form validation Ajax operation, synchronous and asynchronous Simple data lookup with Ajax Ajax costs and benefits
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.