19. AJAX

Source: Internet
Author: User
Tags tojson

The concept of 1.Ajax Ajax is the ability to update parts of a Web page without reloading the entire page (refreshing the page).

The full name of Ajax is Asynchronousjavascript and XML, which is asynchronous Javascript+xml. It is not a new programming language, but a combination of several original technologies.

Advantages of 2.Ajax = = (a) No refresh update data. ==

?? The biggest advantage of Ajax is the ability to communicate with the server to maintain data without refreshing the entire page. This enables the Web application to respond more quickly to user interactions and avoids sending information that is not changed on the network, reducing user latency and bringing a very good user experience.

= = (ii) asynchronous and server communication = =

?? Ajax uses asynchronous methods to communicate with the server, without interrupting the user's operations and having more rapid responsiveness. Optimize communication between browser and server, reduce unnecessary data transfer, time and reduce traffic on network.

= = (iii) front-end and back-end load Balancing = =

?? Ajax can pass on some of the previous server workloads to the client, take advantage of the client's idle ability to handle, reduce server and bandwidth burden, save space and broadband rental costs. and reduce the burden of the server, the principle of Ajax is "on-demand data", can minimize the redundancy request and response to the burden on the server, improve site performance.

How the 3.Ajax works

?? Ajax works by adding a middle-tier (Ajax engine) between the user and the server, making the user operation asynchronous with the server response.

?? Ajax has the core of ++javascript, XMLHttpRequest, dom++ objects, through the XMLHttpRequest object to send an asynchronous request to the server, obtain data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server.

4. Extensions: Synchronous and asynchronous

Asynchronous: Simultaneous execution, also called concurrency
Synchronization: Executes in step order, one line of execution

5. Extensions: Programs, processes, and threads

A program is a collection of instructions,
The procedure to be executed is called a process,
The number of executions is a thread.

6. Writing steps

Ajax requests:
1. Creating an Ajax Object
2. Connect to the server
3. Sending the request
4. Receive return (Ajax returns a string)

Js:function Ajax (Url,fnwin,fnfaild) {//1. Buy phone (Create Ajax object) var xhr = window. XMLHttpRequest? New XMLHttpRequest (): New ActiveXObject ("Microsoft.XMLHTTP");//xmlhttprequest, IE8 incompatible//2. Dial (connect to server) Xhr.open ("    GET ", url,true);    First parameter: Delivery mode getOrPost//second parameter: Requested URL address//third parameter: Async true: Async false: Synchronous default: True//3. Speak (send request) xhr.send ();                 4. Listen (receive return) Xhr.onreadystatechange = function () {if (xhr.readystate = = = 4) {if (Xhr.status = = = 200) {                if (typeof Fnwin = = ' function ') {Fnwin (xhr.responsetext);                }}else{if (typeof fnfaild = = ' function ') {fnfaild (); }}}}}html:<! DOCTYPE html>
Ajax Object-oriented encapsulation
var ajax = {};ajax.get = function(url,fn){    var xhr = new XMLHttpRequest();    xhr.open(‘get‘,url);    xhr.send();    xhr.onreadystatechange = function(){        if(xhr.readyState === 4 && xhr.status === 200){            if(typeof fn === ‘function‘){                fn(xhr.responseText);            }        }    }}ajax.post = function(url,data,fn){    var xhr = new XMLHttpRequest();    xhr.open(‘post‘,url);    //设置请求头    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=utf-8");    xhr.send(data);    xhr.onreadystatechange = function(){        if(xhr.readyState === 4 && xhr.status === 200){            if(typeof fn === ‘function‘){                fn(xhr.responseText);            }        }    }}
(c) Open method:
    1. The URL is a path relative to the current page, or you can use an absolute path
    2. The open method does not send a real request to the server, which is the equivalent of initializing the request and preparing to send it.
    3. Requests can only be sent to URLs that use the same protocol and port in the same domain, otherwise they will be given an error for security reasons
(d) Post parameters:

Send form data

==xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded; Charset=utf-8"); = =

(v) Request status monitoring

==1. onReadyStateChange (state change event) = =
++1) ReadyState property: Request Status + +

A) 0: The request is not initialized (open () has not been called yet)

b) 1: The request has been established, but has not been sent (has not yet called Send ())

c) 2: Request sent, in process (usually can now get the content header from the response)

d) 3; Request in processing, there is usually some data available in the response, but the server does not have a build to complete the response.

e) ++==4==: The response is complete and you can get and use the server's response. ++

2) ==status property: request result = =
Extended:

201-206 indicates that the server successfully processed the status code of the request, which indicates that the Web page can be accessed normally.
The ==200 (successful) server has successfully processed the request. Typically, this indicates that the server provided the requested Web page. ==

4XX indicates a possible error in the request and interferes with the server's processing.
==404 (not found) The requested webpage was not found by the server. ==

First, JS parsing json

(i) ==eval () method = =: The most common way to parse JSON data is to use the Eval () method of JavaScript, with the following code:

function toJson(str){   var json = eval(‘(‘ + str + ‘)’);   return json;}

+ + This method has a performance and security problem and is not recommended for use. ++

(ii) ==json.parse () method = =
This method only supports ie8/firefox3.5+/chrome4/safari4/opera10 and above, these browsers are already close to the standard, the Tojson method is implemented by default. The code is as follows:

function toJson(str){     return JSON.parse(str);}

(iii) ==new function method = =: Code as follows

function toJson(str){    var json = (new Function(“return” + str))();    return json;}
Second, local data refresh

(i) Request and display a static TXT file

    1. Character Set encoding (three buttons to read three different files and deposit in Div)
    2. Cache, block cache (? T=newdate (). GetTime ())

(ii) Dynamic Data: Request JSON file

    1. Pagination

      III. Application of event delegation iv. separation of front and back

200 (success) The server has successfully processed the request. Typically, this indicates that the server provided the requested Web page.

19. AJAX

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.