1 / 49

Ajax

Ajax. JavaScript & jQuery the missing manual Chapter 11. 1. Objective. You will be able to Write JavaScript code that communicates with the server without doing a postback.

jesse
Télécharger la présentation

Ajax

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. Ajax JavaScript & jQuery the missing manual Chapter 11 1

  2. Objective • You will be able to • Write JavaScript code that communicates with the server without doing a postback. • Use jQuery functions to perform asynchronous communication between JavaScript code in the browser and C# code in the server. 2

  3. Ajax • Asynchronous JavaScript and XML • Not a product or a technology. • A catchy name for a way to improve the user experience by reducing delays due to postbacks and page replacments. • Compare google maps to the original version of mapquest. 3

  4. Ajax • Name coined by Jesse James Garrett in an online article Feb. 18, 2005: http://www.adaptivepath.com/ideas/essays/archives/000385.php • Ajax technologies • JavaScript • XMLHttpRequest • CSS • XML • Don’t confuse “Ajax” with Microsoft’s Ajax enabled components. 4

  5. Using XMLHttpRequest • The JavaScript object XMLHttpRequest supports asynchronous communication with the server. • Send a Get or Post message to the server. • Don’t wait for a response. • Continue script operation. • JavaScript event fires when response is received from the server. • Event handler invokes a JavaScript callback function. • Callback function updates the page • by modifying the DOM 5

  6. Using XMLHttpRequest • Has no necessary connection with XML. • JSON is favored by many JavaScript programmers. • JavaScript Object Notation • Get a text message back from the server. • Can be XML, JSON, or anything else. • Client and server have to agree on how to interpret the message. • If the message is XML or JSON we have good support for parsing and using it in both the DOM API and jQuery. 6

  7. Using XMLHttpRequest • The bad news: • Creating an XMLHttpRequest object is browser dependent. • Three different ways to create the object depending on which browser is running the script. • The good news: • jQuery hides the browser differences. 7

  8. How to Use XMLHttpRequest Create an XMLHttpRequest object. Specify a URL and method (Get/Post) Send the request. Handle response event. jQuery make this easy. Hides most of the complexity. http://api.jquery.com/category/ajax/ 8

  9. Simplest Ajax Demo • Just load an HTML file into the current page without doing a postback.

  10. Using Ajax with jQuery Create a new C# ASP.NET empty web site. Ajax_jQuery_Demo Add New Item: Web Form Default.aspx Download jQuery http://docs.jquery.com/Downloading_jQuery#Download_jQuery Add to website. Add New Item: JScript File Ajax_jQuery_Demo.js 10

  11. Default.aspx

  12. File to Load • Add a new HTML file to the website • hello.html • This is the file that we will add to the page asynchronously. • Delete all of the initial boilerplate provided by Visual Studio • Add a single <h1> tag

  13. hello.html

  14. Loading HTML Asynchronously • The jQuery function load • Requests a specified URL from the server. • Appends the HTML to the selected object • JavaScript & jQuery the missing manual, pages 349-356 • http://api.jquery.com/load/

  15. Loading HTML Asynchronously • The jQuery function load We will need a <div> element with ID of Message.

  16. Default.aspx • We need to call Load_HTML in response to a user click. • Add some text and a button to Default.aspx as shown on the next slide. • Note that we do not want a postback when the button is clicked. • input type will be button, not submit. • Just call Load_HTML when the button is clicked. • Set a breakpoint on the Page_Load method to verify that there is not postback.

  17. Default.aspx Try it!

  18. The App Started

  19. Load Done End of Section

  20. Retrieving Dynamic Content Normally we will not want to retrieve a file from the server. Typically we want something computed by server code. Let’s change our script to get content supplied by code running on the server. First just static text. Then result of a computation. Add a new web form to the web site ajax_responder.aspx 20

  21. ajax_responder.aspx Delete everything from ajax_responder.aspx except the Page directive . The response will consist of output from server side code. 21

  22. ajax_responder.aspx.cs 22

  23. The jQuery Get Method • We will use the jQuery get() method to retrieve data from the server asynchronously. • Without a postback. • Uses the JavaScript XMLHttpRequest • Hides browser differences. • Hides differences between get and post. • JavaScript & jQuery the missing manual, pages 356-358, 365-370 • http://api.jquery.com/jQuery.get/

  24. The jQuery Get Method $.get(url, data, callback) • url • Page to request • Must be a page on the same server • data • Query string or JavaScript object literal to send to server • callback • Function to process result • Note that there is no jQuery selector • $ stands alone

  25. The Callback Function • Takes two parameters, both strings • data • Whatever the server sent as its response • status • 'success' or error message

  26. The jQuery text() Method • We will use the jQuery text() method to update the page. • The jQuery text() method, called with a string argument, replaces the text of the selected element with the argument.

  27. Ajax_Query_Demo.js

  28. Update Default.aspx Try it!

  29. Initial Screen

  30. After Click

  31. Chrome

  32. Firefox

  33. Safari End of Section

  34. Sending Data to the Server • Usually we will send some information to the server on an Ajax request. • Used by the server in processing the request.

  35. Passing Request Info to the Server To pass request information to the server in a GET, put it into a query string. Use the query string in the second argument to $.get() Let’s modify the Ajax demo to get the server to add two numbers input by the user. Add a new Web Form. Ajax_Calculation.aspx Set it as the start page. Add a new function to Ajax_jQuery_Demo.js Compute_Sum() Add a new ASPX page to handle the Ajax request. Server_Calculation.aspx Details on following slides. 35

  36. Reality Check • Keep in mind that this is a very simple example, to illustrate the mechanism. • Not realistic! • In the real world, functions invoked by Ajax calls need to do a lot of work in order to justify the message cost. • Work that is not practical to do on the browser in JavaScript.

  37. TextBox1 ASPX Controls TextBox2 btnComputeSum Ajax_Calculation.aspx

  38. Source View

  39. Ajax_Calculation.aspx.cs The code behind has nothing to do. Set breakpoint. (Should not be hit.)

  40. “The jQuery Way” Ajax_jQuery_Demo.js $(document).ready( function() { $('#btnComputeSum').bind('click', Compute_Sum); }); • This anonymous function will be executed when the page has been loaded on the browser. • The “bind” says to execute the JavaScript Compute_Sum function when btnComputeSum is clicked. • The Compute_Sum function will receive a jQuery Event object as input parameter.

  41. “The jQuery Way” function Compute_Sum(evt) { $.get('Server_Calculation.aspx', 'input1=' + $('#TextBox1').val() + '&input2=' + $('#TextBox2').val(), Process_Result); evt.preventDefault(); } • Browser will request Server_Calculation.aspx using the get method. • Second argument is the query string • Built using contents of the two TextBoxes • Example: input1=3&input2=4 • Third argument is the callback function to be executed when the result is received from the browser. • preventDefaultsupresses postback due to click on a submit. • Prevent the normal action for the event. URL Query String Callback Function

  42. “The jQuery Way” function Process_Result(result, status) { if (status=='success') { $('#Result').text(result); } else { $('#Result').text('ERROR ' + result); } } • The callback function. • result is whatever the server code sends. • If calculation is successful, the calculation result. • If error, an error message.

  43. The jQuery Functions

  44. Server Code • JavaScript for the browser is complete. • Now we need to write the code that will run on the server. • Add a new ASPX page to handle the Ajax request. • Server_Calculation.aspx • Delete the boilerplate in the .aspx file.

  45. Server_Calculation.aspx

  46. Server_Calculation.aspx.cs using System; public partial class Server_Calculation : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string input1 = Request.QueryString["input1"]; string input2 = Request.QueryString["input2"]; Decimal augend = 0.00M; Decimal addend = 0.00M; if (Decimal.TryParse(input1, out augend)) { if (Decimal.TryParse(input2, out addend)) { Decimal sum = augend + addend; Response.Write(sum.ToString()); } else { Response.Write("Second input is not a valid numeric value"); } } else { Response.Write("First input is not a valid numeric value"); } } } Try it!

  47. Ajax Calculation in Action

  48. Invalid Input

  49. References • Documentation for the jQuery methods that we have used can be found in JavaScript & jQuery the missing manual and on the jQuery web site. • bind pages 177-179 • http://api.jquery.com/bind/ • load page 349 • http://api.jquery.com/load/ • get pages 356-358 • http://api.jquery.com/jQuery.get/ • text page 139 • http://api.jquery.com/text/#text2 • preventDefault pages 175, 237-238 • http://api.jquery.com/event.preventDefault/

More Related