AJAX Overview and implementation Process _ basics

Source: Internet
Author: User
Tags http request prepare response code

An overview of Ajax

1, Ajax is asynchronous ([ə ' sɪŋkrənəs) JavaScript XML shorthand, not a new technology, but the comprehensive utilization of existing technologies. This technology can request additional data to the server without refreshing the page, bringing a better user experience

2, the core of Ajax technology is the XMLHttpRequest object (referred to as XHR), this is first introduced by Microsoft a feature. Prior to the advent of XHR, Ajax-style communications had to be implemented using some hack means, mostly with hidden or inline frames.

3. XHR provides a fluent interface for sending requests to the server and analyzing the server response. The ability to get more information from the server asynchronously means that after a user clicks, you can get new data without refreshing the page. That is, you can use the XHR object to get new data and then insert the new data into the page through the DOM

4, although the AJAX name has XML component, but, AJAX communication and data format is irrelevant, this technology is not need to refresh the page can get data from the server, but not necessarily the XML data

II. operations: Ajax encapsulated in native Ajax and jquery

1. Native Ajax:

Ajax Effect: Send request (set request Setrequest) receive response (GetResponse)

A, Ajax native Way to send A request:

The most important and fixed part of Ajax is the HTTP request.

1) To establish the connection: (IE7 and above versions are supported XMLHttpRequest)

var xhr = new XMLHttpRequest(); //创建异步请求对象

2 GET Request: Format must be (url?name1=value1&name2=value2)

Xhr.open ("Get", "01-register.php?name=" +name);//Initialize asynchronous GET request
xhr.send (null);//Connect to Server

3) Post request

Xhr.open (' Post ', ' 01-xmlhttprequest-test.php ');/Request message Line
Xhr.setrequestheader (' Content-type ', ' application/ X-www-form-urlencoded '); /*post Request Set Request head */
xhr.send (' name=rose&age=20 ');//Request Style

4 The difference between get and POST requests:

★get does not need to set the request header, and post needs to set the request header

★get data passes through URLs, and post data is passed in the Send method

B, Ajax native Way to receive the response:

/* The response of the listening server
/* Xhr.onreadystatechange=function () {/
* Determines whether the current response was successful 1. The server responded 2. The result of the response is correct
 /if (xhr.status ==200 && xhr.readystate==4) {
 var result=xhr.responsetext;
 Console.log (result); Output data obtained from the server
 //Then the data can be processed accordingly
 }
 };

C, processing response data:

 /* Monitor
 /xhr.onreadystatechange=function () {
 if (xhr.status==200 && xhr.readystate==4) {//* State of judgment *
 * var result;
 /* Get the content-type*/
 var ct=xhr.getresponseheader ("Content-type") in the response message;
 /* Judge Content-type, parse the data * *
 /if (Ct.indexof ("xml")!=-1) {
 result=xhr.responsexml;
 }
 else if (Ct.indexof ("JSON")!=-1) {
 result=json.parse (xhr.responsetext);
 }
 else{
 result=xhr.responsetext;
 }
 /* Call callback Function-Delegate-agent * *
 Success && success (result);
 

Ajax encapsulated in jquery

 $.ajax ({
 Type: Request Method (Get/post),
 URL: "register.php", data
 : Send request data,
 beforesend:function () { Returns false to cancel this Ajax request},
 success:function (result) {After a successful response call},
 Error:function (ERR) {error response called},
 complete : function () {Call when response completes (including success and Failure)}
 });

jquery provides a special way to serialize a form:

 $('form').serialize():   //序列化表单(即格式化key=val & key=val);

Third, response

We need to listen to the response state of the server and then handle the data obtained from the server.

1 onReadyStateChange is a JavaScript event, used to monitor the state of the XMLHttpRequest

2) readystate: Response status, returns the current status of the XMLHTTP request

readyState State

Status description

(0) not initialized

This phase confirms that the XMLHttpRequest object is created and is ready for an uninitialized turn to invoke the open () method. A value of 0 indicates that the object already exists, or the browser will complain--the object does not exist.

(1) Loading

This phase initializes the XMLHttpRequest object by calling the open () method, which finishes setting the object state based on the parameter (method,url,true). and call the Send () method to start sending the request to the server. A value of 1 indicates that a request is being sent to the server.

(2) Loading complete

This phase receives server-side response data. However, only the original data of the service-side response is obtained and cannot be used directly from the client. A value of 2 indicates that the full response data has been received. and prepare for the next phase of data parsing.

(3) Interactive

This phase resolves the received server-side response data. That is, the data is converted to a format that can be accessed through the responsebody, ResponseText, or Responsexml properties based on the MIME type returned by the server-side response header to prepare for the client invocation. State 3 indicates that data is being parsed.

(4) Complete

This phase confirms that all data has been resolved to a format that is available to the client and that parsing is complete. A value of 4 indicates that the data has been parsed and can be obtained by XMLHttpRequest the corresponding property of the object.

3 Status: The response code for the server

Common response code: 200-Server successfully returned Web page

404-Request page does not exist

503-Service Not available

For more information about the server response code, see ———— Network Transport Protocol (HTTP protocol)

The above is the content of this article, there is a need to see, I hope to help you. Thanks for the support of the cloud-dwelling community!

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.