Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 32 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
32
Dung lượng
1,65 MB
Nội dung
CSCI 6962: Server-side Design and Programming Introduction to AJAX Client/Server Model Request Client Response Server Large Document • 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 AJAX Model Request JavaScript Server Response Web Page Small Data • 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 XMLHttpRequest Object JavaScript in Browser Server XMLHttpRequest • 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 XMLHttpRequest Object • XMLHttpRequest object 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 XMLHttpRequest object directly in JavaScript so object created automatically XMLHttpRequest Object Will use this object in code Example • “Greeting” example – – – – Reads name from text element Sends to getGreeting servlet Reads response Displays in another text element username=John JavaScript Text element getGreeting Hello John! Server JavaScript Page Structure Button contains onClick() call to JavaScript greet() function Opening Link to Server • Syntax: request.open(method, URL, asynchronous); GET or POST XMLHttpRequest (usually POST) object created previously true if asynchronous, false otherwise The URL of the server, including the servlet name and any parameters • Syntax if server requires name and password: request.open(method, URL, asynchronous, name, password); Adding Parameters to URL • Data passed to server in form of request http://domain/servletname?name=value&name=value&… URL Parameters appended • Extract information from form (using JavaScript/DOM) • Append to URL to pass to server • Open that URL form.username.value Status Checking • Can track progress of response – Keep user up to data on status request.readystate – Returns number indicating status of request (loading) Request object created, but send method not called (loaded) send method called, but response not yet available (interactive) Some data received, and responseText will give current partial results (completed) All data received Status Checking Display message while waiting Display response when loaded 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 AJAX in browser Server form data errors form submission next page Validation servlet Next page JSP Validation • Client-side validation – Form can call function when SUBMIT button pressed – If function returns false, form not submitted function validateFunction() { validate form data if (form valid) return true; else return false; } 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 data response = request.responseText; if (response != “”) { ok = false; display error message in response } } return ok; } Validation Must validate quantity entered by user So call validateQuantity before form submitted Validation If no errors, return empty string Send message back to client Do validation checks and create appropriate error message 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) 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 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.) AJAX in browser request data about state of game Server moves change game state database Other players Servlet game state Game database form submission Other players Timer Events • Simple example: Server returns random number every time called by a client Timer Events • Create timer object in JavaScript • Attach timer to JavaScript function: window.setInterval(functionName, interval); Function to call at Interval in regular intervals miliseconds • Initialize inside function called when page loaded function intitializerFunction() { window.setInterval(functionName, interval); } … Timer Events timer object declared globally startTimer called when page loaded readFeed called every second (1000 ms) Field where “feed” displayed Timer Events • Call to server best if asynchronous – Call to server may take longer than interval – Potential problems if JavaScript tries to call function again before previous call done – Asynchronous form avoids by creating separate process each time Timer Events • Update page when response returned from server ... 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 AJAX in browser Server form... Create servlet to handle request – Gets data from request as before • Writes result to response object – Create printWriter to response object using getWriter() – Write string to printWriter... JavaScript/DOM) • Append to URL to pass to server • Open that URL form.username.value Adding Parameters to URL Extract the value of the username field of the form form Append to request in name=value