Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Brief introduction and basic summary of AJAX

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "introduction and basic summary of AJAX". In daily operation, I believe many people have doubts about the introduction and basic summary of AJAX. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "introduction and basic summary of AJAX"! Next, please follow the editor to study!

This section provides an introduction to (Asynchronous Link Server object) XMLHTTPRequest and AJAX.

AJAX is "Asynchronous Javascript And XML" (asynchronous JavaScript and XML). AJAX has four advantages: 1. That is, it reduces the burden on the server. 2 brings a better user experience. 3. Based on standards is widely supported. 4. Have better page rendering and data separation.

Technical name Technical description

Javascript javascript is a general scripting language. AJAX is written in javascript.

The style of the css user interface is modified through css

DOM DOM modifies DOM,ajax through javascript to change the user interface at run time, or to update a node in the page locally.

The XMLHttpRequest XMLHttpRequest object XMLHttpRequest object allows web programmers to retrieve data from the web server in the background. The number of data is usually XML or text.

As we can see from the above, javascript pastes the various parts together like glue, such as changing and refreshing the user interface through javascript operation BOM, and changing the css style by modifying className

1. Asynchronous object connection server

Loosely speaking, ajax is a simple multithreading that allows users to perform multiple operations in the foreground without interruption. Ajax Asynchronous interaction works silently in the background Asynchronous access in web is achieved through the XMLHttpRequest object, which was first introduced as an activeX control in ie5. Then various browsers support the asynchronous object one after another, and the object must be created first. The code is as follows:

The copy code is as follows:

Var xmlHttp

Function createXMLHrrpRequest () {

If (window.ActiveXObject)

XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP")

Else if (window.XMLHttpRequest)

XmlHttp = new XMLHttpRequest ()

}

The object first creates a global variable xmlHttp and leaves it for later use in the function. In addition, create the asynchronous object function createXMLHrrpRequest ()

This process uses the if statement method, if the IE uses the window.ActiveXobject method, if not, use the XMLHttpRequest method to create the function.

After you have created an asynchronous object, it is natural to use it to connect to the server, which has a series of useful properties and methods.

Property / method description

Abort () cancel the request

GetAllResponseHeaders () gets the specified http header

Open (method,url) create request, method specifies the request type, GET POST

Send () sends the request

SetRequestHeader () specifies the http header of the request

Event control object in case of any state change in onreadystatechange

ReadyState

Status of the request

0 is not initialized yet

1: the request is being sent

2 to complete the request

3 data is being received for successful request.

4 successful receipt of data

ResponseText server returns text

ResponseXML server returned xml

Status

The http request response value returned by the server, commonly used are

200 indicates that the request is successful

202 indicates that the request was received, but the processing was not completed

400 indicates an incorrect request

404 indicates that the resource was not found

500 indicates an internal server error, such as an aspx code error

After creating the XMLHttpRequest object, first use the open () method to establish a request and send it to the server. The complete expression of this method is as follows:

Open (methond,url,asynchronous,user,password)

Where method represents the type of request, and the general length is GET,POST.

Url is the requested address, either absolute or relative.

Asynchronous is a Boolean value indicating whether it is an asynchronous request. The default value is asynchronous request true.

User and password are optional usernames and passwords respectively.

After you create an asynchronous object, you can use the following code to make a request to the server:

XmlHttp.open ("GET", "1-1.aspx", true)

The above code uses the get method to request a page with a relative address of 9-1.aspx, which is asynchronous. After the request is made, you need the status readyState attribute of the request to determine the situation of the request. If this attribute changes, the onreadystatechange event will be triggered, so the usual code is as follows:

The copy code is as follows:

XmlHttp.onRecorderStateChange = function () {

If (xmlHttp.readyState = = 4)

/ / execute the relevant code

}

That is, write the event function of onRecorderStateChange directly, and continue if the state of readyState is 4 (data reception is successful). But usually, you need to judge not only the status of the request, but also the status status returned by the server, so the above code is changed to

The copy code is as follows:

XmlHttp.onRecorderStateChange = function () {

If (xmlHttp.readyState = = 4 months & xmlHttp.status==200)

/ / execute the relevant code

}

The above two pieces of code just set up the request and need to use the send () method to send the request, which is based on the following prototype:

Send (body)

The change method has only one parameter, body, which represents the data to be sent to the server in the form of a query string, such as:

Var body = "myName=isaac&age=25"

If get mode is specified in open, these parameters are submitted as query strings, or as POST methods of HTTP if post mode is specified. For send (). The body parameter is required, and if no data is sent, you can use the

XmlHttp.send (null)

Specifically, if you use the POST method to submit a request, you must use the following statement to set the header of the HTTP before sending it. The syntax is as follows:

XmlHttp.setRequestHeader ("content-Type", "application/x-www-form-urlencoded;")

After receiving the client request, the server returns the corresponding result according to the request, which is usually in two forms, one is in text form, which is stored in responseText, and the other is in XML format, which is stored in responseXML. The client program can perform string processing on the former and DOM-related processing on the latter, for example, it can do the following processing on the server return value:

Alert ("Server returns:" + xmlHttp.responseText)

The whole process of asynchronously connecting to the server is as follows:

The copy code is as follows:

Var xmlHttp

Function createXMLHttpRequest () {

If (window.ActiveXObject)

XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP")

Else if (window.XMLHttpRequest)

XmlHttp = new XMLHttpRequest ()

}

Function startRequest () {

CreateXMLHttpRequest ()

XmlHttp.open ("GET", "http://study.ahthw.com/ajaxresponse/1-1.aspx", true)

XmlHttp.onreadystatechange = function () {

If (xmlHttp.readyState = = 4 & & xmlHttp.status = = 200)

Alert ("Server returns:" + xmlHttp.responseText)

}

XmlHttp.send (null)

}

In order to solve the problem of asynchronous connection ie caching, you need to add a parameter related to time milliseconds to the real address, so that the address of each request is different. And this parameter server is really not needed.

The copy code is as follows:

Var sUrl = "1-1.aspx?" + new Date (). GetTime (); / / address is constantly changing

XMLHttp.open ("GET", sUrl,true)

2.GET and POST mode

In the above example, no additional data is sent to the server other than requesting the asynchronous server, and there are usually get and post modes in the html request, both of which can be used as a way to send data in an asynchronous request.

If it is a GET request, the data is put directly into the URL address of the asynchronous request, while the send method does not send any data, for example:

The copy code is as follows:

Var queryString = "firstName=isaac&birthday=0226"

Var sUrl = "1-1.aspx?" + queryString + "& timestamp" + new Date () .getTime ()

XmlHttp.open ("GET", sUrl)

XmlHttp.send (null); / / this statement only sends null

In the case of POST mode, the data is uniformly sent in the send () method, the request address has no information, and the request header must be set, for example:

The copy code is as follows:

Var queryString = "firstName=isaac&birthday=0226"

Var sUrl = "1-1.aspx?" + queryString + "& timestamp" + new Date () .getTime ()

XmlHttp.open ("POST", sUrl)

XmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")

XmlHttp.send (queryString); / / this statement is responsible for sending data

Example

To demonstrate the difference between GET and POST more clearly, write the sample code, first create two text boxes for entering the user's name and birthday, and set up two buttons for the GET and POST methods to send asynchronous requests

The copy code is as follows:

The data filled in by the user is written in the function createQueryString () and transferred when needed. The code is as follows

The copy code is as follows:

Function crrateQueryString () {

Var firstName = document.getElementById ("firstName") .value

Var birthday = document.getElementById ("birthday") .value

Var queryString = "firstName=" + firstName + "& birthday=" + birthday

Return queryString

}

After receiving the request data, the server returns the corresponding text according to different times, and the client receives the text and displays it in the corresponding div cache. The code is as follows

The copy code is as follows:

Function handleStateChange () {

If (xmlHttp.readyState = = 4 & & xmlHttp.state = = 200) {

Var responseDiv = document.getElementById ("serverResponse")

ResponseDiv [XSS _ clean] = xmlHttp.responseText

}

}

GET and POST each set up their own functions doRequestUsingGET () and doRequestUsingPOST ().

The complete code is as follows:

The copy code is as follows:

Var xmlHttp

Function createXMLHttpRequest () {

If (window.ActiveXObject)

XmlHttp = new ActiveXObject ("Microsoft.XMLHttp")

Else if (window.XMLHttpRequest)

XmlHttp = new XMLHttpRequest ()

}

Function createQueryString () {

Var firstName = document.getElementById ("firstName") .value

Var birthday = document.getElementById ("birthday") .value

Var queryString = "firstName=" + firstName + "& birthday=" + birthday

Return encodeURI (encodeURI (queryString)); / / twice coding to solve the problem of Chinese garbled code

}

Function doRequestUsingGET () {

CreateXMLHttpRequest ()

Var queryString = "1-3.aspx?"

QueryString + = createQueryString () + & timestamp= + new Date () .getTime ()

XmlHttp.onreadystatechange = handleStateChange

XmlHttp.open ("GET", queryString)

XmlHttp.send (null)

}

Function doRequestUsingPOST () {

CreateXMLHttpRequest ()

Var url = "1-3.aspx timestamp =" + new Date () .getTime ()

Var queryString = createQueryString ()

XmlHttp.open ("POST", url)

XmlHttp.onreadystatechange = handleStateChange

XmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")

XmlHttp.send (queryString)

}

Function handleStateChange () {

If (xmlHttp.readyState = = 4 & & xmlHttp.status = = 200) {

Var responseDiv = document.getElementById ("serverResponse")

ResponseDiv [XSS _ clean] = decodeURI (xmlHttp.responseText); / / Decoding

}

}

The server side mainly returns different strings according to the user input and the type of request.

The copy code is as follows:

You can see from the above code that both POST and GET send asynchronous requests for data, usually using GET when there is not much data and POST when there is more data.

When using PSOT to send Chinese characters, post reception will garbled, and it is normal to use GET to send Chinese characters. This is because the asynchronous object xmlHttp is encoded according to UTF-8 when processing the returned responseText.

The usual solution is to escape () encode the sent data and then use unescape () to decode the returned responseText. However, escape () and unescape () are generally not recommended in javascript programming. EncodeURI () and decodeURI () are recommended. To work here, the data sent must be encodeURI () encoded twice.

The code is as follows

The copy code is as follows:

Function createQueryString () {

Var firstName = document.getElementById ("firstName") .value

Var birthday = document.getElementById ("birthday") .value

Var queryString = "firstName=" + firstName + "& birthday=" + birthday

Return encodeURI (encodeURI (queryString)); / / twice coding to solve the problem of Chinese garbled code

}

And decode again when the data responeText is returned, the code is as follows

The copy code is as follows:

Function handleStateChange () {

If (xmlHttp.readyState==4&&xmlHttp.status = = 200) {

Var responeDiv = document.getElementById (serverResponse)

ResponeDiv [XSS _ clean] = decodeURI (XMLHttp.responseText); / / Encoding

}

}

In this way, Chinese can also be used in POST mode.

3. The server returned xml

XML is an Extensible markup language (Extensible Markup Language), it is a customizable markup language, used to overcome the limitations of html, according to the actual function, xml is mainly used for data storage.

In ajax, if the server returns XML, it can be obtained through the responseXML attribute of the asynchronous object, and developers can use the action method of DOM to deal with it.

Suppose the server returns

The copy code is as follows:

Member List

Isaac

W13

Jun 24th

Cancer

1118159

Fresheggs

W610

Nov 5th

Scorpio

1038818

Girlwing

W210

Sep 16th

Virgo

1307994

Tastestory

W15

Nov 29th

Sagittarius

1095245

Lovehate

W47

Sep 5th

Virgo

6098017

Slepox

W19

Nov 18th

Scorpio

0658635

Smartlau

W19

Dec 30th

Capricorn

0006621

Tuonene

W210

Nov 26th

Sagittarius

0091704

Dovecho

W19

Dec 9th

Sagittarius

1892013

Shanghen

W42

May 24th

Gemini

1544254

Venessawj

W45

Apr 1st

Aries

1523753

Lightyear

W311

Mar 23th

Aries

1002908

Here, use the asynchronous object to get the XML, and list all the items in the table. The method of initializing the object is exactly the same as getting the text. The code is as follows:

The copy code is as follows:

Var xmlHttp

Function createXMLHttpRequest () {

If (window.ActiveXObject)

XmlHttp = new ActiveXObject ("Mincrosoft,XMLHttp")

Else if (window.XMLHttpRequest)

XmlHttp = new XMLHttpRequest ()

}

An asynchronous request occurs when the user clicks the button and gets the responseXML object, as follows

The copy code is as follows:

Function getXML (addressXML) {

Var sUrl = addressXML + "? timestamp=" + new Date ()

CreateXMLHttpRequest ()

XmlHttp.onRecorderStateChange = handleStateChange

XmlHttp.open ("GET", url)

Xml.send (null)

}

Function handleStateChange () {

If (xmHttp, readyState = = 4 & & xmlHttp.status = = 200)

DrawTable (xmlHttp.responseXML); / / responseXML gets the xml document

}

Where DrawTable () is a function for logistics processing XML, passing the XML object responseXML returned by the server directly as a parameter. The HTML section is as follows:

The copy code is as follows:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report