Silicon Valley _ajax_ Learning notes __ajax

Source: Internet
Author: User
What is Ajax

Ajax technology is generated Ajax is considered (asynchronous JavaScript and XML abbreviation). Now, technology that allows browsers to communicate with the server without refreshing the current page is called Ajax. The name "Ajax" was created in February 2005 by Jesse James Garrett of Adaptive Path in his article ajax:a New approach to WEB application. And Ajax is the technology that Google labs Google to publish Google Maps and Google suggest after the real people know.

Ajax: A way to communicate with the server without refreshing the entire page


Figure 1 The traditional model of the Web. The client sends a request to the server, the server returns the entire page, so repeatedly


Figure 2 in the AJAX model, data is transmitted independently between the client and the server. The server no longer returns the entire page

Ways to communicate with the server without refreshing the entire page:
-Flash
-Java applets
-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
-Hidden IFRAME
- XMLHttpRequest: This object is an extension of JavaScript to enable Web pages to communicate with the server. is the best choice for creating Ajax applications. In fact, Ajax is usually used as a synonym for XMLHttpRequest objects. The working schematic diagram of Ajax

Ajax Toolkit

Ajax is not a new technology, it's actually a few technologies, each of which is doing its job and aggregating in a whole new way.

Server-side language: The server needs to have the ability to send specific information to the browser. Ajax has nothing to do with server-side languages.

XML (extensible Markup Language, Extensible Markup Language) is a format that describes data. XML is one of the options for AAJX programs that require some form of formatting to pass information between the server and the client.

XHTML (eXtended hypertext Markup Language, using extended hyper-media markup Language) and CSS (cascading style Sheet, cascading style sheets) to standardize rendering;

The DOM (Document Object model, the Documentation objects module) implements dynamic display and interaction;

Asynchronous data reads using the XMLHTTP component XMLHttpRequest Object

Using JavaScript to bind and handle all data ajax flaws

Ajax is not the perfect technology. With Ajax, some of its flaws have to weigh the following: browser-compatible page refreshes caused by Javascript and AJAX engines, resulting in failed functions such as rewind. Streaming media support is not as good as Flash or Java applets. Some handheld devices (such as cell phones, PDAs, etc.) are poorly supported. Overview of the XMLHttpRequest XMLHttpRequest was first implemented in IE5 as an ActiveX component. Non-consortium standards. Create a XMLHttpRequest object (not uniform because of nonstandard implementation methods)
Internet Explorer implements XMLHttpRequest as an ActiveX object in other browsers (Firefox, Safari, Opera ...). ) to implement it as a local JavaScript object. XMLHttpRequest implementations on different browsers are compatible, so you can access the properties and methods of the XMLHttpRequest instance in the same way, regardless of how the instance is created. Creating XMLHttpRequest Objects

To save a little time each time you write Ajax, you can package the contents of object detection into a reusable function:

Description: For window. A XMLHttpRequest call returns an object or a null,if statement that considers the result returned by the call to be true or False ( False if returned object is true). If the XMLHttpRequest object exists, the value of the XHR is set to a new instance of the object. If it does not exist, to detect the existence of activeobject instances, if the answer is yes, the Microsoft XMLHTTP new instance to the XHR XMLHttpRequest method

Properties of XMLHttpRequest

Send Request

Using the XMLHttpRequest instance to communicate with the server consists of the following 3 key parts: onReadyStateChange Event handler function Open method Send method

onReadyStateChange: The event handler is triggered by the server, not the user 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. Each readyState property change triggers the ReadyStateChange event

Open (Methods, URLs, Asynch): The Open method of the 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 a query string attached 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 in the same URL. If the response to each request is different, it can lead to bad results. By appending the timestamp to the end of the URL, you can ensure that the URL is unique, thereby avoiding browser caching results. URL: The path string that points to the file on the server you are requesting. can be an absolute or relative path. Asynch: Indicates whether the request is to be transmitted asynchronously, and the default value is true. Specify True, you do not need to wait for the server to be appropriate before reading the following script. Specify false, and when the script process passes this, it stops and waits until the AJAX request is finished before continuing.

Send (data): The Open method defines some details of the Ajax request. The Send method sends instruction data to a standby request: A string that will be passed to the server. If a GET request is selected, no data is sent, and null can be passed to the Send method: Request.send (NULL); When you supply a parameter to the Send () method, make sure that the method specified in open () is post, and null is used if no data is sent as part of the request body. Complete Ajax GET Request sample:

setRequestHeader (Header,value) when the browser requests a page from the server, it sends a set of header information along with the request. These header information is a series of meta data (metadata) that describes the request. The header information is used to declare whether a request is a get or a POST. In an AJAX request, the task of sending header information can be setrequestheader by the complete parameter header: The name of the header; Argument value: The value of the 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 has been encoded with the URL. The method must be open () before the full Ajax POST request sample is invoked:
Receive Response

You can send a request to the server using the XMLHttpRequest method. The following properties of XMLHttpRequest can be changed by the server during the Ajax process:
-ReadyState
-Status
-ResponseText
-Responsexml

The ReadyState 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 yet
1 represents being loaded. The Open method has been invoked, but the Send method has not yet been invoked
2 The representative has finished loading. Send has been invoked. Request already started
3 represents the interaction. The server is sending a response
4 delegates completed. The ReadyStateChange event is triggered by a change in the ReadyState value each time the response is sent. If you assign the onReadyStateChange event handler function to a function, the change of each readyState value will cause the function to be executed. Changes in readyState values vary depending on the browser. However, when the request ends, each browser sets the value of the readyState to 4

Each response sent by the status server also has the header information. 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 Not Found page (not found)
403 No access (forbidden)
500 Internal server error (internal service error)
2001-Cut Normal (OK)
304 is not modified (not modified) in the XMLHttpRequest object, the status code sent by the server is stored in the status attribute. By comparing this value to 200 or 304, you can ensure that the server has sent a successful response

The ResponseText property of the ResponseText XMLHttpRequest contains 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 attribute. The Responsexml property is available only if the server sends data with the correct header information. MIME type must be a text/xml data format feed

AJAX on the server side is a language-independent technology. You can use any server-side language at the business logic level.
When receiving data from the server side, the 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
-HTML XML

Advantage: XML is a common data format. Instead of imposing data into a defined format, you need to customize the appropriate markup for your data. The DOM allows you to take full control of the document.

Disadvantage: If the document comes from the server, it must be guaranteed that the document contains the correct header information. If the document type is incorrect, then the Responsexml value will be empty. DOM parsing can be complex when the browser receives a long XML file, JSON

JSON (JavaScript Object notation) is a simple data format that is lighter than XML. JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

The rule of JSON is simple: an object is an unordered set of ' name/value pairs '. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma).

JSON Sample

JSON assigns a value with a colon rather than an equal sign. Each assignment statement is separated by a comma. The entire object is encapsulated in curly braces. Nested data can be graded with curly braces. The data stored in the object description can be a string, a number, or a Boolean value. Object descriptions can also store functions, which is the object's method. parsing JSON

JSON is just a text string. It 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 will take a string as its argument. The string is then executed as JavaScript code. Because the string of JSON is composed of JavaScript code, it is executable in itself.

code example:

JSON provides a json.js package that, after downloading Http://www.json.org/json.js, uses the Parsejson () method to parse the string into a JS object

JSON Summary

Advantage: As a data transmission format, JSON is similar to XML, but it is more agile.
JSON does not need to send header information containing a specific content type from the server side.

Disadvantage: Syntax too rigorous code not easy to read eval function exists risk HTML parsing HTML 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 data from the ResponseText property. It is already in the desired format and can be inserted directly into the page. The easiest way to insert HTML code is to update the InnerHTML property of this element. HTML Summary

Advantage: The HTML code sent from the server side does not need to be parsed with JavaScript on the browser side. HTML is good for readability. The HTML code block is highly efficient with the InnerHTML attribute.

Disadvantage: If you need to update multiple parts of a document via AJAX, HTML is not appropriate
InnerHTML is not a DOM standard. Comparison Summary

If an application does not need to share data with other applications, using HTML fragments to return data is the simplest

If the data needs to be reused, the JSON file is a good choice and has an advantage in terms of performance and file size

XML documents are preferred when remote applications are unknown, because XML is the Ajax of "Esperanto" in Web Services domain jQuery

jquery 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 () l Oad () method

The 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 the JQuery selector to specify the target location for the HTML fragment, and then the URL of the file to be loaded as a parameter passed to the load () method

load () method-Details If you only need to load certain elements within the target HTML page, you can achieve the goal by using the URL parameter of the load () method. By specifying the selector with the URL parameter, you can easily select the desired content from the loaded HTML document. The syntax for the URL parameter of the load () method is "URL selector" (Note: There is a space between the URL and selector): The transfer parameters of the load () method are based on the parameter data. If there is no parameter pass, use get way to pass, otherwise use POST method for the operation that must be completed before loading, the load () method provides the callback function, which has three parameters: represents the data of the request return content; The Textstatus object and the XMLHttpRequest object $.get () (or $.post ()) method , which represents the request state, $.get () method uses the Get method to make asynchronous requests. Its structure is: $.get (url[, data][, callback][, type]);

The callback function of the $.get () method has only two parameters: the data represents the returned content, can be XML document, JSON file, HTML fragment, etc. The textstatus represents the request status, which may be: Succuss, error, notmodify, timeout 4. $.get () and $.post () methods are global functions in JQuery, and find () is the JQ Uery an object to manipulate a method to serialize an element

JQuery provides a simplified way to prepare for "key/value data sent to the server": Serialize (). This method is used in a JQuery object to serialize the contents of DOM elements into strings for Ajax requests.

Use the Serialize () method to automatically URL-encode parameters because the method is used for JQuery objects, so not only can the form be used, but also the elements selected by other selectors can use it. Demo: Validate Date

Key to date validation: Java Regular expression classes: Java.util.regex.Pattern Java Date Validation regular expressions, including run February:

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.