1. What is Ajax? * Asynchronous JavaScript and XML: Asynchronous JS and XML * It can use JS to access the server, but also asynchronous access! * The response of the server to the client is generally the entire page, an HTML full page! But in Ajax because it is a partial refresh, then the server will no longer respond to the entire page! And just data! > Text: Plain text > XML: Everyone is familiar with!!! > JSON: It is the data interaction format provided by JS, which is most popular in Ajax! 2. Asynchronous and synchronous Interaction * Synchronization: > Send a request, waiting for the server to end the response before sending a second request! The middle of this time is a word "card" > Refresh is the entire page! * Async: > Send a request without waiting for a response from the server, then you can send a second request! > can use JS to receive the response of the server, and then use JS to local refresh! 3. Ajax Scenarios * Baidu search Box * User registration (verify that the user name is registered) 4. Advantages and Disadvantages of Ajax: * Asynchronous Interaction: Enhanced User experience! * Performance: Because the server does not need to respond to the entire page, only need to respond to partial content, so the server pressure is reduced! Cons: * Ajax can't be applied in all scenarios! * Ajax has increased the number of accesses to the server, causing pressure on the server! ====================================================================================ajax sends an asynchronous request (four-step operation) 1. First step (Get XMLHttpRequest) * Ajax actually only need to learn an object: XMLHttpRequest, if mastered it, mastered the ajax!!! * Get XMLHttpRequest > Most browsers support: var xmlHttp = new XMLHttpRequest (); > Ie6.0:var xmlHttp = new ActiveXObject ("Msxml2.xmlhttp"); > IE5.5 with an earlier version of Ie:var xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP"); * Write function f to create XMLHttpRequest objectUnction createxmlhttprequest () {try {return new XMLHttpRequest (); } catch (e) {try {return new ActiveXObject ("Msxml2.xmlhttp"); } catch (e) {try {return new ActiveXObject ("Microsoft.XMLHTTP"); } catch (e) {alert ("Dude, what browser are you using?") "); Throw e; }}}}2. Second step (open connection to server) * Xmlhttp.open (): Used to open a connection to the server, it requires three parameters: > Request: Can be a GET or post > Request URL: Specify server-side resources, such as;/day23_1/aservle T > whether the request is asynchronous: If true means sending an asynchronous request, otherwise synchronizing the request! * Xmlhttp.open ("GET", "/day23_1/aservlet", true); 3. Step three (send request) * Xmlhttp.send (NULL): If not given may cause some browsers to fail to send! > Parameters: Is the request body content! If it is a GET request, NULL must be given. 4. Step fourth () * Register listener on an event of the XMLHTTP object: onReadyStateChange * XMLHTTP Object A total of 5 states: > 0 Status: Just created, not yet called the Open () method; > 1 Status: Request start: Call the Open () method, but haven't called the Send () method > 2 state: The Send () method has been called; > 3 Status: The server has started responding, but does not indicate that the response is over! > 4 Status: Server Response end! (usually we only care about this state!!!) ) * Get the status of the XmlHttp object: > var state = xmlhttp.readystate;//may be 0, 1, 2, 3, 4 * Get the status code of the server response > var status = xmlhttp.status;//For example 200, 404, 500 * Get the server response content 1 > var content = Xmlhttp.responset ext;//gets the contents of the text format of the response of the server > var content = xmlhttp.responsexml;//Gets the response of the server to the contents of the XML response, it is the Document Object! Xmlhttp.onreadystatechange = function () {//xmlhttp 5 states will call this method if (xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {///double-judge: Determine whether it is a 4 state, and also to determine whether 200//Gets the response content of the server var text = Xmlhttp.responsetext; }};==================================================================================== The second example: sending a POST request ( If you need to send a request with parameters, usually with a POST request) * Open:xmlHttp.open ("post" ...); * Add a step: Set Content-type request Header: > Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); * Send:xmlHttp.send ("Username=zhangsan&password= 123 ");//Specify the request body ==================================================================================== when sending the request The third example: Check the registration form of the user is registered! 1. Write page: * ajax3.jsp > Give registration Form page > Add onblur Event Listener to User name textbox > Get text box contents, send to Server by ajax4 step, get response result * If 1: in text Box shows "user name has been registered" * If 0: do nothing! 2. Write the servlet * validateusernameservlet > get the user name parameters passed by the client > determine if Itcast * Yes: return 1 * No: return 0=============== ===================================================================== response content is XML data * Server side: > Set response header: ContentType, The value is: Text/xml;charset=utf-8 * client: > var doc = xmlhttp.responsexml;//Gets the Document Object! ===================== The fourth example: the response content is XML data ============================================================================ ======== The fifth example: the provinces and cities linkage 1. Page<Selectname= "Province"> <option>= = = Please select province = = =</option> </Select> <Selectname= "City"> <option>= = = Please select city = = =</option> </Select>2. Provinceservlet * Provinceservlet: Request This servlet! immediately after the page has been loaded > It needs to load the China.xml file and send all the province names using strings to the client! 3. Work on the page * get this string, separated by commas, get the array * loop through each string (the name of the province), use each string to create a<option>Element is added to the<Selectname= "Province">this element is in 4. Cityservlet * Cityservlet: Send a request when the page chooses a province! * Get the name of the province, load the China.xml file, query the corresponding element object in the province! , the element is converted to an XML string and sent to the client 5. Work on the page * put<Selectname= "City">Delete all of the child elements in, but do not delete<option>= = = Please select city = = =</option>* Get the server response result: doc!!! * Get all the< City>Child elements, looping through, getting< City>the contents * use each< City>The content creates a<option>element, which is added to the<Selectname= "City">====================================================================================xstream1. What role * The JavaBean can be converted to (serialized) XML2. XStream Jar Package * Core jar package: Xstream-1.4.7.jar; * Must be dependent on package: xpp3_min-1.1.4c (XML Pull Parser, a fast XML parser); 3. Use step * XStream XStream = new XStream (); * String xmlstr = xstream.toxml (JavaBean); 4. Use details * Aliases: Modify the element name corresponding to the type > Xstream.alias ("China", List.class): Let the List type generate the element named China > Xstream.alias ("Province", P Rovince.class): Let the province type generate an element named province * Used as a property: A member of the default class, resulting in a child element of the element! We want the members of the class to generate the attributes of the element > xstream.useattributefor (province.class, "name"): the name of the province class is called the name member, which generates<Province>The name attribute of the element * Removes the collection type of fame: we only need to collection the content, and do not want collection itself to generate an element > xstream.addimplicitcollection ( Province.class, "Cities"): Make the name of the province class cities (it is a list type, its contents will also generate elements) of fame does not generate elements * Remove the specified fame of the class, so that it does not generate XML elements > Xstream.omitfield (City.class, "description"): the corresponding element named description of the City class will not appear in the generated XML! ====================================================================================json1. What is JSON? * It is a data interchange format provided by JS! 2. JSON syntax * {}: is an Object! > attribute names must be enclosed in double quotes! Single citation not!!! > property Value: * NULL * NUMERIC * String * array: Use [] Enclose * Boolean: true and False3. Apply JSON * var person = {' name ': ' Zhangsan ', ' age ': ' Sex ': ' Male '};4. JSON vs. xml comparison * readability: XML WINS * Parsing difficulty: JSON itself is the JS object (home combat), so much simpler * popularity: XML has been popular for many years, but in the Ajax field, JSON is more popular. -----------------------------------JSON-LIB1. What is it? * It can convert JavaBean to JSON string 2. Jar Package * Slightly 3. Core class * Jsonobject---MAP > ToString (); > Jsonobject map = jsonobject.fromobject (person): Convert object to Jsonobject Object * Jsonarray, List > toString () > Jsonarray JSONArray = Jsonobject.fromobject (list): Convert list to Jsonarray object
Ajax and the inside of the XStream "Dark Horse Programmer _ ultra-comprehensive javaweb video tutorial Vedio"