1 / 34

CSCI 6962: Server-side Design and Programming

CSCI 6962: Server-side Design and Programming. Introduction to AJAX. Client/Server Model. Request. Response is entire web page Very inefficient High network costs Must be loaded into browser and rendered

trella
Télécharger la présentation

CSCI 6962: Server-side Design and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCI 6962: Server-side Design and Programming Introduction to AJAX

  2. Client/Server Model Request • Response is entire web page • Very inefficient • High network costs • Must be loaded into browser and rendered • Problem:Browser itself cannot get any data from server without requesting entire page Client Server Response Large Document

  3. AJAX Model Request • Based on JavaScript running in browser • JavaScript code sends data to server, reads response • Response is simple data instead of entire page • Modifies page without re-rendering it completely • AJAX:Asynchronous JavaScript and XML Web Page Server JavaScript Response Small Data

  4. XMLHttpRequest Object • XMLHttpRequest object acts as “link” to server • Sends request to given URL (including “form data”) • Allows access to status of request • Acts as reference to data sent back from server as response Server JavaScript in Browser XMLHttpRequest

  5. XMLHttpRequest Object • XMLHttpRequestobject represented differently on different browsers • Microsoft browsers represent as ActiveX • Other browsers support directly • Must use “browser safe” JavaScript to create • Provide method to check capabilities and return object • Place declaration of XMLHttpRequestobject directly in JavaScript so object created automatically

  6. XMLHttpRequest Object Will use this object in code

  7. Example • “Greeting” example • Reads name from text element • Sends to getGreetingservlet • Reads response • Displays in another text element username=John Text element getGreeting Server JavaScript Hello John!

  8. JavaScript Page Structure Button contains onClick()call to JavaScript greet()function

  9. Opening Link to Server • Syntax:request.open(method, URL, asynchronous); GET or POST (usually POST) true if asynchronous, false otherwise XMLHttpRequest object created previously The URL of the server, including the servlet name and any parameters

  10. Adding Parameters to URL • Data passed to server in form of requesthttp://domain/servletname?name=value&name=value&… • Extract information from form (using JavaScript/DOM) • Append to URL to pass to server • Open that URL Parameters appended URL form.username.value

  11. Adding Parameters to URL Extract the value of the usernamefield of the formform Append to request in name=value format Form name = “form” Field name = “username”

  12. Sending Request/Receiving Response • Send request to server:requestObject.send(); • Get response back from server as string:result =requestObject.responseText; • Note: These commands must be in JavaScript try/catchblock in case no access to server

  13. Manipulating Page • Use response to then manipulate page using JavaScript/ Document Object Model • Form element values • Document properties • Inserting new content…

  14. Creating Content at the Server • Create servlet to handle request • Gets data from requestas before • Writes result to response object • Create printWritertoresponseobject using getWriter() • Write string to printWriterusingprint(String)method

  15. Asynchronous Access • Getting response from server may take time • Slow network access, lengthy response … • Continue with other tasks while waiting for response • Spawn separate asynchronous process to handle response when it arrives Get information from form Open request to server Send request Wait for response When response received, handle it (possibly changing page Continue other tasks(user interface, animation,etc.)

  16. Asynchronous Access • Set asynchronous parameter to true in open • request.onreadystatechangedefines function to be called by asynchronous processrequest.onreadystatechange = functionName Send request request.onreadystatechange = functionName function functionName(){ Wait for response When response received, handle it } Continue other tasks(user interface, animation,etc.)

  17. Asynchronous Access

  18. Status Checking • Can track progress of response • Keep user up to data on status request.readystate • Returns number indicating status of request

  19. Status Checking Display message while waiting Display response when loaded

  20. Validation • Problem: Validation costly in client/server model • Single error requires reload of entire page • AJAX solution: • Use AJAX to send form data to server for validation • Receive any error messages as response • Submit form only if no errors Server Validation servlet Next page JSP AJAX in browser form data errors form submission next page

  21. Validation • Client-side validation • Form can call function when SUBMIT button pressed<form action = “nextPage”onSubmit = return validateFunction()> • If function returns false, form not submittedfunction validateFunction() {validate form dataif (form valid) return true; else return false;}

  22. Validation • Validation outline using AJAX: function validate() {var ok = true; // Any errors yet?for (all elements on form we must validate) {append form data to URL send request to validation servlet for that dataresponse = request.responseText; if (response != “”) { ok = false;display error message in response } } return ok;}

  23. Validation Must validate quantity entered by user So call validateQuantity before form submitted

  24. Validation If no errors, return empty string Do validation checks and create appropriate error message Send message back to client

  25. Validation Get quantity from form and submit to servlet If no error message returned, return true (allows form submit) Otherwise, display error message and return false (prevents form submit)

  26. Timed Events • Appearance: “Continuous feed” from server • Form field regularly updated by server • AJAX Implementation: • Timer in JavaScript calls function at regular intervals • Function calls server-side servlet for current data • Displays current data on form

  27. Timer Events • Servlet creates illusion of “real-time” data • Get input from sensors, etc. at regular intervals • Based on data submitted asynchronously by other users (online gaming, etc.) request data about state of game moves change game state database Other players Server Servlet Game database AJAX in browser Other players game state

  28. Timer Events • Simple example: Server returns random number every time called by a client

  29. Timer Events • Create timer object in JavaScript • Attach timer to JavaScript function:window.setInterval(functionName, interval); • Initialize inside function called when page loadedfunction intitializerFunction() {window.setInterval(functionName, interval);}…<body onLoad = “initializerFunction()”> Function to call at regular intervals Interval in miliseconds

  30. Timer Events timerobject declared globally startTimercalled when page loaded readFeedcalled every second (1000 ms) Field where “feed” displayed

  31. Handling Lack of JavaScript • Client browser must have JavaScript enabled for AJAX to work • Not always true (mobile browsers, etc.) • Must still give some response if no AJAX • Submit form data using standard client-server model • Send entire page back as response

  32. Handling Lack of JavaScript • Create a “backup” page on server to call if AJAX not supported:

  33. Handling Lack of JavaScript • Call that page when form submitted as action • Also call JavaScript AJAX function using onSubmit (as in validation example) • Button must now be type=“submit”

  34. Handling Lack of JavaScript • JavaScript functiononSubmit()calls returns false • If JavaScript enable, server call prevented • Otherwise, server call made by default

More Related