Java_web Learning (+) Ajax

Source: Internet
Author: User

Ajax

Ajax (asynchronous JavaScript and XML abbreviations),the technology that allows the browser to communicate with the server without having to refresh the current page is called Ajax。 Ajax:a way to communicate with the server without having to refresh the entire pageThe traditional model of the Web, the client sends a request to the server, and the server returns the entire page, so repeatedly. (left) in the AJAX model, the data is transferred independently between the client and the server. The server no longer returns the entire page. (Right image)

The way to communicate with the server without having to refresh the entire page:

1>flash 2>java Applet 3> Framework: If you use a set of frames to construct a Web page, you can update only one of the frames without disturbing the entire page 4> the hidden iframe 5>xmlhttprequest: This object is an extension to JavaScript that allows the Web page to communicate with the server. is the best choice for creating Ajax apps. In fact, Ajax is often used as a synonym for XMLHttpRequest objects.

working principle of Ajax

Ajax Toolkit

Ajax is not a new technology, it is actually several technologies, each of which is a new way of aggregating together.       1> server-side language: The server needs to have the ability to send specific information to the browser, and Ajax is independent of the server-side language. 2>xml (extensible Markup Language, Extensible Markup Language) is a format for describing data, AAJX programs need some format to pass information between server and client, XML is one of the options 3>xhtml (EX Tended hypertext Markup Language, using Extended hypermedia Markup Language) and CSS (cascading style Sheet, cascading style sheets) to standardize the presentation; 4>dom (Document Object Model , document Object model) for dynamic display and interaction; 5> using XMLHTTP component XMLHttpRequest object for asynchronous data reading 6> binding and processing all data using JavaScriptthe drawbacks of AjaxAjax is not the perfect technology, using AJAX, some of its flaws have to weigh: 1> by Javascript and the AJAX engine caused by the browser compatible 2> page local refresh, resulting in functions such as backward failure.       3> Streaming Media Support no flash, Java applet is good. 4> some handheld devices (such as mobile phones, PDAs, etc.) are poorly supported.Overview of XMLHttpRequestXMLHttpRequest was first implemented in the form of ActiveX components in IE5, non-standard, creating XMLHttpRequest objects (the implementation method is not uniform due to non-standard) 1>internet The Explorer implements XMLHttpRequest as an ActiveX object 2> other browsers (Firefox, Safari, Opera ...).       ) to implement it as a local JavaScript object. 3>xmlhttprequest implementations on different browsers are compatible, so you can access the properties and methods of the XMLHttpRequest instance in the same way, no matter what method the instance creates.Create a XMLHttpRequest objectTo save a little time each time you write Ajax, you can package the object detection into a reusable function: Description: To Window . The XMLHttpRequest call returns an object or a null,if statement that returns the result of the call as true or false (or False if the returned object is true). If the XMLHttpRequest object exists, the value of XHR is set to a new instance of the object. If it does not exist, it detects if the Activeobject instance exists, and if the answer is yes, it assigns a new instance of Microsoft XMLHTTP to XHRmethods and properties of XMLHttpRequestSend RequestUsing XMLHttpRequest instances to communicate with the server consists of the following 3 key parts: A complete Ajax GET Request Example: complete Example of an Ajax POST request:
// onreadystatechange event handler function // Open Method //
 // onreadystatechange:  //  //  during Ajax execution, the server notifies the client of the current state of communication. This is accomplished by updating the readyState of the XMLHttpRequest object. Changing the ReadyState property is a way for the server to connect to the client. The ReadyStateChange event is triggered every time the ReadyState property is changed  
 // open (method, URL, asynch)  // xmlhttprequest object allows the programmer to send a request to the server with an Ajax call.  // method: The request type, a string similar to "GET" or "POST". If you want to retrieve only one file from the server without sending any data, use get (you can send the data in a GET request by appending the query string to the URL, but the data size is limited to 2000 characters). If you need to send data to the server, use post.  //  In some cases, Some browsers cache the results of multiple XMLHttpRequest requests at the same URL. If the response to each request is different, it will result in bad results. When you append the timestamp to the end of the URL, you can ensure that the URL is unique, thus avoiding the browser caching the results.  // url: path string that points to the file on the server you requested. Can be either an absolute path or a relative path.  // asynch: Indicates whether the request is to be transmitted asynchronously, and the default value is true. Specifies true to not wait for the server to be appropriate before reading the following script. Specifies false, when the script process passes this point, to stop until the AJAX request has been executed before proceeding. 
 // send (data):  // open method defines some details of the Ajax request. The Send method sends an instruction  //  //  //   
// setRequestHeader (Header,value) // when the browser requests a page from the server, it sends a set of header information along with the request. The header information is a series of metadata that describes the request (metadata). The header information is used to declare whether a request is a GET or POST. //// parameter header: Name of the header;   The value of the parameter value: header.  // If you send data to the server with a POST request, you need to set the header of "Content-type" to "application/x-www-form-urlencoded". It tells the server that the data is being sent, and that the data is already URL-encoded.  // The method must be open () before it can be called

Receive Response

Use the XMLHttpRequest method to send a request to the server. In the process of Ajax processing, the following properties of XMLHttpRequest can be changed by the server:

// readyState // Status // ResponseText // Responsexml
//readyState//the ReadyState property represents the current state of the AJAX request.        Its value is represented by a number. //0 represents uninitialized. The Open method has not been called//1 represents loading. The open method has been called, but the Send method has not yet been called//2 indicates that the load is complete. Send has been called. The request has started//3 represents the interaction. The server is sending a response//4 represents complete. Response sent complete//each time the ReadyState value changes, the ReadyStateChange event is triggered. If the onReadyStateChange event handler is assigned to a function, then each change in the ReadyState value causes the function to execute. //changes in the ReadyState values vary depending on the browser. However, when the request is finished, each browser will set the value of the readyState to 4 uniformly
//Status//each response sent by the server also comes with a header message. The three-digit status code is the most important header information in the response sent by the server and is part of the Hypertext Transfer Protocol. //common status codes and their meanings://404 Page Not Found (not found)//403 No access (forbidden)//500 Internal Server error (internal service error)//2001 cut Normal (OK)//304 Not modified (not modified)//In the XMLHttpRequest object, the status codes sent by the server are saved in the status attribute. By comparing this value to 200 or 304, you can ensure that the server has sent a successful response
// ResponseText // The ResponseText property of XMLHttpRequest contains the data sent from the server. It is a html,xml or plain text, depending on what the server sends.  // when the ReadyState property value becomes 4 o'clock, the ResponseText property is available, indicating that the AJAX request has ended. 

// Responsexml // If the server returns XML, the data is stored in the Responsexml property.   The Responsexml property is available only when the server sends the data with the correct header information. The MIME type must be Text/xml

Data Format Feed

On the server side AJAX is a language-independent technology.       What server-side languages are used at the business logic level. When receiving data from the server side, those data must be sent in a format that the browser can understand. The server-side programming language can only return data in the following 3 formats: XML, JSON, HTMLXMLPros: 1>xml is a common data format.            2> does not have to impose data on a defined format, but rather to customize the appropriate markup for the data.       3> uses the DOM to take full control of the document. Cons: 1> If the document comes from the server, you must ensure that the document contains the correct header information.           If the document type is incorrect, then the value of Responsexml will be empty. 2> DOM parsing can be complicated when a long XML file is received by the browserJSONJSON (JavaScript Object Notation) is a simple data format that is lighter than XML.       JSON is a native JavaScript format, which means that working with JSON data in JavaScript does not require any special APIs or toolkits. The rules of JSON are simple: an object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends.                                                                        Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma). JSON assigns a value with a colon (not an equal sign). Each assignment statement is separated by commas. The entire object is enclosed in curly braces. You can use curly braces to rank nested data. The data stored in the object description can be a string, a number, or a Boolean value.        Object descriptions can also store functions, which are methods of objects. Parsing Json:json is just a text string that is stored in the ResponseText property.In order to read the JSON data stored in the ResponseText attribute, you need to base the Eval statement on JavaScript. The function eval treats a string as its argument. The string is then executed as JavaScript code. Because the JSON string is made up of JavaScript code, it is executable by itself.code Example:        JSON provides a json.js package, after downloading Http://www.json.org/json.js, use the Parsejson () method to parse the string into a JS object JSON summary: Advantages:              1> as a data transfer format, JSON is similar to XML, but it is more dexterous.        2>json does not need to send header information from the server side that contains a specific content type. Disadvantage: 1> Grammar is too rigorous 2> code is not easy to read 3>eval function riskHTMLHTML is made up of some plain text. If the server sends HTML through XMLHttpRequest, the text is stored in the ResponseText property.You do not have to read the data from the ResponseText property. It is already in the desired format and can be inserted directly into the page. The simplest way to insert HTML code is to update the InnerHTML property of this element. Pros: 1> HTML code sent from the server side does not need to be parsed by JavaScript on the browser side.             The readability of the 2>html is good.       The 3>html code block is highly efficient with the InnerHTML attribute. Cons: 1> If you need to update multiple parts of a document via AJAX, the HTML is inappropriate 2>innerhtml is not a DOM standard.Comparison Summary1> If the application does not need to share data with other applications, the simplest 2> when using HTML fragments to return data if the data needs to be reused, the JSON file is a good choice, Z has advantages in performance and file size 3> when the remote application is not XML documents are preferred because XML is the "Esperanto" of the Web services domainAjax in JQueryjquery encapsulates Ajax operations, $.ajax () at the bottom of jquery, the second layer is load (), $.get () and $.post (), and the third layer is $.getscript () and $.getjson ()load () methodThe load () method is the simplest and most commonly used Ajax method in jQuery to load remote HTML code and insert it into the DOM. Its structure is: Load (url[, Data][,callback]) programmers only need to use JQuery                                                                       The selector specifies the destination location for the HTML fragment and then passes the URL of the file to be loaded as a parameter to the load () method. If you only need to load certain elements within the target HTML page, you can use the URL parameter of the load () method to achieve the purpose. By specifying the selector with the URL parameter, it is convenient to select the desired content from the loaded HTML document. The URL parameter of the load () method has a syntax structure of "URL selector" (Note: There is a space between the URL and the selector): The pass parameter of the load () method is based on the parameter data from the dynamic custom. If there is no parameter passing, it is passed by GET, otherwise the load () method provides a callback function for operations that must be loaded before it can continue, and the function has three parameters: the XMLHttpRequest object that represents the request return content; Represents the Textstatus object and the XMLHttpRequest object for the request state.$.get () (or $.post ()) methodThe $.get () method uses the Get method to make an asynchronous request. Its structure is: $.get (url[, data][, callback][, type])

Java_web Learning (+) Ajax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.