Ajax Learning (1)-Introduction to Ajax

Source: Internet
Author: User

AjaxIs the abbreviation of Asynchronous JavaScript and XML (and DHTML.

The following is an Ajax applicationProgramThe basic technologies used:
• HTML is used to create a web form and determine the fields used by other parts of the application.
• JavascriptCodeIt is the core code for running Ajax applications and helps improve communication with server applications.
• DHTML or dynamic HTML, used to dynamically update forms. We will use Div, span, and other dynamic HTML elements to mark HTML.
• The Document Object Model Dom is used to process HTML structures (using JavaScript code) and (in some cases) the XML returned by the server.

We can see from the above that AJAX is not a new technology, but a few old technologies are combined with new methods to achieve new results! Many things are diversified. Ajax is a new technology, a new idea, and a new architecture!

The basic working principle and process of Ajax:

In a common web application, enter the form field and clickSubmitButton. Then the entire form is sent to the server, and the server forwards it to the script that processes the form (usually PHP or Java, or CGI process or something similar ), after the script is executed, send it back to the new page. This page may contain html of a new form with some data filled, a confirmation page, or a page with certain options selected based on the input data in the original form. Of course, the user must wait when the script or program on the server processes and returns a new form. The screen becomes blank and will be re-drawn after the server returns data. This is the cause of poor interaction. users do not receive immediate feedback, so they feel different from desktop applications.

In Ajax, JavaScript andXMLHttpRequestPut objects on web forms and serversBetween. When the user fills out the form, the data is sent to some JavaScript code whileNoDirectly sent to the server. On the contrary, JavaScript code captures form data and sends requests to the server. At the same time, forms on the user's screen do not flash, disappear, or delay. In other words, JavaScript code sends a request behind the scenes, and the user does not even know how to send the request. Even better, requests are sent asynchronously, that is, JavaScript code (and users) does not have to wait for the response from the server. Therefore, you can continue to input data, scroll the screen, and use applications.

The server then returns the data to the JavaScript code (still in the web form), which decides how to process the data. It can quickly update the form data, making users feel that the application is completed immediately, the form is not submitted or refreshed, and users get new data. JavaScript code can even execute some calculation on the received data and send another request without user intervention! This isXMLHttpRequest. It can interact with the server as needed, and the user may not even know what happened behind the scenes. The result is similar to the dynamic, rapid response, and highly interactive experience of desktop applications, but it has all the power of the Internet.

XMLHTTPRequest object:

Open (): Create a new request to the server.

Send (): Send a request to the server.

Abort (): Exit the current request.

Readystate: Provides the current HTML readiness status.

Responsetext: Request Response text returned by the server.

Due to the competition between browsers in the past two years, various browsers can obtainXMLHttpRequestObjects use different methods.

Multiple browsers are supported to create XMLHttpRequest objects.

 

Code
VaR XMLHTTP =   False ;
Try {
XMLHTTP =   New Activexobject ( " Msxml2.xmlhttp " );
} Catch (E ){
Try {
XMLHTTP =   New Activexobject ( " Microsoft. XMLHTTP " );
} Catch (E2 ){
XMLHTTP =   False ;
}
}
If ( ! XMLHTTP &&   Typeof XMLHttpRequest ! =   ' Undefined ' ){
XMLHTTP =   New XMLHttpRequest ();
}

The core of this Code is divided into three steps:
1. Create a variable XMLHTTP to reference the XMLHTTPRequest object to be created.
2. Try to create this object in Microsoft browser:
Try to create it using the msxml2.xmlhttp object.
If it fails, try the Microsoft. XMLHTTP object again.
3. If XMLHTTP is still not created, this object is created in a non-Microsoft manner.
Finally, XMLHTTP should reference a valid XMLHTTPRequest object, regardless of the browser that runs.

Request/response in Ajax

Send a request: basically the same process in the Ajax application:
1. obtain the required data from the web form.
2. Create the URL to be connected.
3. Open the connection to the server.
4. Set the function to run after the server is complete.
5. Send the request.

Code
Function Callserver (){
// Get the city and state from the web form
VaR City = Document. getelementbyid ( " City " ). Value;
VaR State = Document. getelementbyid ( " State " ). Value;
// Only go on if there are values for both fields
If (City =   Null ) | (City =   "" )) Return ;
If (State =   Null ) | (State =   "" )) Return ;
// Build the URL to connect
VaR URL =   " /Scripts/getzipcode. aspx? City = "   + Escape (city) +   " & State = "   + Escape (State );
// Open a connection to the server
XMLHTTP. Open ( " Get " , URL, True );
// Setup a function for the server to run when it's done
XMLHTTP. onreadystatechange = Updatepage;
// Send the request
XMLHTTP. Send ( Null );
}

Handling response:

Possible value returned by readystate:

0: Request not initialized (not called yetOpen ()).

1: The request has been created but has not been sent yet (no call has been madeSend ()).

2: The request has been sent and is being processed. (You can obtain the Content Header from the response ).

3: The request is being processed. Generally, some data in the response is available, but the server has not yet completed the response generation.

4: The response has been completed. You can obtain and use the server response.

There must be two points:

1. Do not do anythingXMLHTTP. readystateThe property value is 4.

2. The server will fill in the responseXMLHTTP. responsetextAttribute.

Response Function:

Code
Function Updatepage (){
If (XMLHTTP. readystate =   4 ){
VaR Response = XMLHTTP. responsetext;
Document. getelementbyid ( " Zipcode " ). Value = Response;
}
}

 

 

The initial code uses the basic JavaScript code to obtain the values of several form fields. Set an ASP script as the link target. Pay attention to the method specified by the Script URL. City and State (from the form) are appended after the URL with a simple get parameter.

Then open a connection. This is the first time you seeXMLHttpRequest. The connection method (get) and the URL to be connected are specified. If the last parameter is setTrue, Then an asynchronous connection will be requested (this is the origin of Ajax ). If you useFalseAfter the code sends a request, it will wait for the response returned by the server. IfTrueWhen the server processes requests in the background, users can still use forms (or even call other Javascript methods ).

XMLHTTP(Remember, this isXMLHttpRequestObject instance)OnreadystatechangeThe attribute can tell the server that it is runningCompleteAfter (may take five minutes or five hours. Because the Code does not wait for the server, you must let the server know how to do so that you can respond. In this example, if the server has processed the request, a specialUpdatepage ()Will be triggered.

Finally, use the valueNullCallSend (). Because the data (city and state) to be sent to the server has been added to the request URL, no data needs to be sent in the request. In this way, a request is sent, and the server works according to your requirements.

The following is a summary of the Ajax workflow:

Javascript obtains the parameters or variables to be passed to the server segment, and then uses the createdXMLHTTPRequest objectSend server segments. If the Server accepts the data and returns the data, save it in the responsetext attribute, and finally modify the DOM using JavaScript, so that the client can not modify the data.

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.