230 likes | 377 Views
Chapter 6 JavaScript and AJAX. 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
E N D
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
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
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
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
Adding JavaScript to HTML • JavaScript code can be placed anywhere in an HTML document • Typically placed at the end of <head> • Delimited by <script>…</script> <head> <title>JavaScript Demo</title> <script type="text/javascript"> function sayHello() { alert("Hello!"; } </script> </head>
Invoking JavaScript Code • JavaScript functions can be tied to DOM events on individual HTML elements • using onX="function()", where 'X' is an event <script type="text/javascript"> function color(button, color) { button.style.background=color } </script> <input type="button" value="Click Me" onmouseover="color(this, #FF0000)" onmouseout="color(this, #E0E0E0)" /> Click Me Click Me red gray self-reference
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 DOM Events
Dialog Boxes • Dialog boxes can be used to • inform the user of errors or events • confirm actions initiated by the user
User Action Confirmation Dialog <script type="text/javascript"> function confirmDelete() { var answer = confirm("Are you sure you want" + "to delete this player?"); return answer } </script> <form method="post" action="/delete"> ... <p><input type="submit" value="Delete" onclick="return confirmDelete()" /></p> </form> if the user clicks"Cancel", the form will NOT be submitted
Form Validation <script> function validate() { if (document.getElementById("name").value.length == 0) { alert("Please complete the required fields\n" + "and resubmit."); return false; } return true; } </script> <h3>Add Player:</h3> <form id="form1" action="addplayer" onsubmit="return validate()" > <p>Name: <input type="text" id="name" /></p> ... <p><input type="submit" value="Register" /></p> </form> if the procedure returns false, the form will NOT be submitted
HTML Manipulation <script> 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; } </script> <h3>Add Player:</h3> <form id="form1" action="addplayer" onsubmit="return validate()" > <p><span id="nameflag"></span> Name: <input type="text" id="name" /></p> ... <p><input type="submit" value="Register" /></p> </form>
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
Ajax Setup • An XMLHttpRequest object is created to channel HTTP transactions <script type="text/javascript"> 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; } } } ...
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
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);
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) } <p><input type="text" id="custnr" onkeyup="checkNumber(this.value)" /> <span id="name"></span></p>
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(); } }
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
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