Ajax Asynchronous JavaScript And XML(Asynchronous JavaScipt And XML), Is an asynchronous interactive web development technology , For creating fast dynamic web pages . A small amount of data exchange with the server ,Ajax Asynchronous update of web pages , This means that you can load the entire page without reloading it , Update a part of the web page .

97 Microsoft invented ajax The key technology , And in 99 Year for IE5 in , But unfortunately, it has not been put on hold for other reasons ,ajax The popularity of technology benefits from google To promote .Ajax The core is JavaScript object XmlHttpRequest, It's a technology that supports asynchronous requests , What is its significance :1. Update pages without reloading them .2. Request data from server after page has been loaded .3. Receive data from server after page has been loaded .4. Send data to the server in the background . It should be noted that AJAX It's not a new programming language , It's a way to create better, faster, more interactive Web Application Technology .

1.AJAX How it works :

Ajax The working principle of is equivalent to adding... Between the user and the server — Middle layers (AJAX engine ), Asynchronous user operation and server response . Not all user requests are submitted to the server , image — Some data validation and data processing are handed over to Ajax The engine does it by itself , Only when it is determined that new data needs to be read from the server, can Ajax Engine submits request to server on behalf of .

2.Ajax The advantages of :

1. The biggest point is that the page does not refresh , The user experience is very good .

2. Communicate with the server asynchronously , More responsive .

3. We can transfer the burden of the previous server to the client , Take advantage of the client's idle ability to handle , Reduce the burden of servers and bandwidth , Save space and broadband rental costs . And reduce the burden on the server ,ajax The principle of “ On demand data ”, Minimize redundancy requests , And the burden of response on the server .

4. Based on standardized and widely supported technologies , No need to download plug-ins or applets .

5.Ajax send WEB Interface and application separation in ( It can also be said that data and presentation are separated ), It's good for division of labor and cooperation 、 Reduce the non-technical personnel to the page modification caused by WEB Application error 、 Increase of efficiency 、 It's also more suitable for today's Publishing System .

3.Ajax The shortcomings of :

1、ajax Browser not supported back Button .

2、 safety problem AJAX Exposed the details of the interaction with the server .

3、 Weak support for search engines .

4、 Breaking the exception mechanism of the program .

5、 Not easy to debug .

4.XmlHttpRequest Properties and methods of objects :

attribute

explain

readyState

come into being XMLHttpRequest The state of . from 0 To 4 change .

0: Request not initialized

1: Server connection established

2: Request received

3: Request processing

4: Request completed , And the response is ready

Onreadystatechange

Storage function ( Or function name ), whenever readyState When attributes change , The function will be called .

responseText

The text content of the server response

responseXML

The server responds XML The content corresponds to DOM object

Status

Server returned http Status code .200 Express “ success ”,404 Express “ Not found ”,500 Express “ Server internal error ” etc. .

statusText

The server returns the text message of the status .

Method

explain

Open(string method,string url,boolean asynch,

String username,string password)

Specify the... That interacts with the server side HTTP Method ,URL Address , Other request information ;

Method: Express http Request method , In general use "GET","POST".

url: Represents the address of the requested server ;

asynch: Indicates whether the asynchronous method is used ,true For asynchronous ,false For synchronization ;

The latter two can not be specified ,username and password Represents the user name and password respectively , Provide http The authentication mechanism requires a user name and password .

Send(content)

Make a request to the server , If it's asynchronous , This method immediately returns .

content Can be specified as null Indicates that no data is sent , The content can be DOM object , Input stream or string .

SetRequestHeader(String header,String Value)

Set up HTTP The specified header in the request header The value of is value.

This method needs to be used in open Method is called later , Generally in post Mode .

getAllResponseHeaders()

Return contains Http All response header information for , The corresponding head includes Content-length,date,uri The content such as .

The return value is a string , Contains all header information , Each key name and value is separated by a colon , Between each set of keys CR and LF( Carriage return with line break ) To separate !

getResponseHeader(String header)

return HTTP The key name specified in the response header header Corresponding value

Abort()

Stop current http request . Corresponding XMLHttpRequest Object is reset to an uninitialized state .

I understand above Ajax And how it works and XmlHttpRequest Properties and methods of objects , So how do we use it ? Here I'll do it in five steps .

First step : establish XmlHttpRequest object :

1
2
3
4
5
6
7
var  xmlhttp =  null ;
//XMLHttpRequest IE6 There are compatibility issues , Can be judged ie6 Of  ActiveXObject('Microsoft.XMLHTTP')
if (window.XMLHttpRequest){
     xmlhttp = new  XMLHttpRequest(); // except IE6 Other browsers
} else {
     xmlhttp = new  ActiveXObject( "Microsoft.XMLHTTP" ); //IE6 browser
}

The second step : Specify the link address :

1
var  url= 'demo.php' .

The third step : Send resource request to server .

Use xmlhttprequest Object's open() and send() Method to send a resource request to the server .

xmlhttp.open(method,url,async) method Include get and post,url Mainly the path of the file or resource ,async Parameter is true( On behalf of the asynchronous ) perhaps false( On behalf of the synchronization )

xmlhttp.send(); Use get Method to send the request to the server .

xmlhttp.send(string); Use post Method to send the request to the server .

post When can the send request be used ?

(1) When updating a file or database .

(2) Send a lot of data to the server , because post There is no character limit to the request .

(3) Send encrypted data entered by user .

get Example :

1
2
3
4
xmlhttp.open( "GET" "ajax_info.txt" true );
xmlhttp.open( "GET" "index.html" true );
xmlhttp.open( "GET" "demo_get.asp?t="  + Math.random(),  true );xhttp.send();
xmlhttp.send( null ); // For passing parameters , But only in use post It's only useful when you submit a request in this way

post Example :

1
2
xmlhttp.open( "POST" "demo_post.asp" true );
xmlhttp.send();

post Form example :

1
2
3
xmlhttp.open( "POST" "ajax_test.aspx" true );
xmlhttp.setRequestHeader( "Content-type" "application/x-www-form-urlencoded" );
xmlhttp.send( "fname=Henry&lname=Ford" );

Step four : Server response

Use xmlhttprequest Object's responseText or responseXML Property to get the response from the server .

responseText: Get response data as a string .

responseXML: get XML Response data in form .

If the response from the server is not XML, Please use responseText attribute .

responseText Property returns a response as a string , So you can use it like this :

responseText Example :

1
document.getElementById( "demo" ).innerHTML=xmlhttp.responseText;

If the response from the server is XML, And it needs to be XML Object parsing , Please use responseXML attribute :

responseXML Example :

1
2
3
4
5
6
7
xmlDoc = xhttp.responseXML;
txt =  "" ;
x = xmlDoc.getElementsByTagName( "ARTIST" );
for  (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue +  "<br>" ;
}
document.getElementById( "demo" ).innerHTML = txt;

Step five :onreadystatechange Use of functions

onreadystatechange function , When sending a request to the server , If we want the server response to perform some functions, we need to use onreadystatechange function , Every time xmlhttprequest Object's readyState Change will trigger onreadystatechange function .

onreadystatechange Property to store a when readyState Functions that are automatically called when a change occurs .

readyState attribute ,XMLHttpRequest Object state , Change from 0 To 4,0 Represents that the request was not initialized ,1 On behalf of the server connection success ,2 The request was received by the server ,3 Processing requests ,4 Request complete and response ready .

status attribute ,200 Indicates a successful response ,404 Indicates that the page does not exist .

stay onreadystatechange Incident , Occurs when the server is ready to respond , When readyState==4 and status==200 The server is ready to respond .

1
2
3
4
5
6
7
xmlhttp.onreadystatechange= function ()
   {
   if  (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById( "demo" ).innerHTML=xmlhttp.responseText;
     }
   }

VC & Delphi

A callback function is a function that is passed as an argument to another function .

If there are more than one AJAX Mission , Then you should create XMLHttpRequest Object to write a standard function , And for each AJAX The task calls the function .

The function call should contain URL And happen onreadystatechange Tasks performed on event ( Each call may be different ):

1
2
3
4
5
6
7
function  myFunction(){
     loadXMLDoc( "/try/ajax/ajax_info.txt" , function ()
     {
         if  (xmlhttp.readyState==4 && xmlhttp.status==200)
         {
             document.getElementById( "demo" ).innerHTML=xmlhttp.responseText;        }
     });}

In practical use , Try to take advantage of events +ajax to button Bind click event , And then execute ajax.

server.php

<?php
if (isset($_POST['action']))
{
switch($_POST['action'])
{
case "btn1":btn1();break;
case "btn2":btn2();break;
default:break;
}
} function btn1()
{
echo "hello Button 1";
}
function btn2()
{
echo "hello Button 2";
} ?>

The way :index.php

<html>
<head>
<style>
div {width:600px;margin:200px auto;} .btn {
background-color:#44c767;
-moz-border-radius:28px;
-webkit-border-radius:28px;
border-radius:28px;
border:1px solid #18ab29;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:17px;
padding:16px 31px;
text-decoration:none;
text-shadow:0px 1px 0px #2f6627;
}
.btn:hover {
background-color:#5cbf2a;
}
.btn:active {
position:relative;
top:1px;
} #btn2 {float:right;}
</style>
<script type="text/javascript" language="javascript">
var xmlHttp;
function createXMLHttpRequest(){
// Check whether the browser supports XMLHttpRequest object
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function fun(n){
createXMLHttpRequest();
var url="server.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = callback;
xmlHttp.send("action=" + n.value);
}
function callback(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
</script>
</head> <body>
<div>
<button type="button" class="btn" id="btn1" onclick="fun(this)" value="btn1"> Button 1</button>
<button type="button" class="btn" id="btn2" onclick="fun(this)" value="btn2"> Button 2</button>
</div>
</body> </html>

Ajax More related articles on the notes of

  1. AJax Study note 2 (onreadystatechange The role of )

    AJax Study note 2 (onreadystatechange The role of ) When a request is sent , The client is not sure when the request will be completed , So we need to use the event mechanism to capture the state of the request XMLHttpRequest The object provides on ...

  2. be based on PHP Of AJAX Learning notes ( course )

    Reprinted from :http://www.softeng.cn/?p=107 This is what I'm learning ajax Notes on the process , Through the study of this note , Can finish ajax A quick start to . The front end of this note uses the original javascript ...

  3. AJAX Learning notes

    AJAX Not a programming language ,AJAX It's a technology to load web pages asynchronously , That is, the content of the web page can be partially updated without refreshing the web page . Such as : Submit form information , adopt ajax You don't have to refresh the page to make people understand how to fill in the information correctly , Judge the error in filling in the information or ...

  4. Jquery ajax Learning notes

    My js & jq Always a rookie level , I'm not busy recently ajax Knowledge of , Some of the contents in this paper are referred to here & here   Always used before js Write ajax Now based on jq It's much easier to implement ~ $.get & $. ...

  5. Ajax Learning notes 2 The use of Ajax and XML

    <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using Ajax wit ...

  6. Ajax Learning notes 1 First of all Ajax Applications

    Code <head> <title>An Ajax demo</title> <script src="../js/jquery-1.4.1.js&q ...

  7. Ajax Learning notes ( Two )

    Two .prototype Ku explained in detail 1.prototype Library usage // Import and download ok prototype.js file <script type="text/javascript" ...

  8. ajax Learning notes ( Native js Of ajax)

    ajax It's a server-side language independent technology , It can be used in any language environment web project ( Such as JSP,PHP,ASP etc. ). ajax advantage : 1) Dynamic data interaction without page refresh 2) Partial refresh page 3) Beautiful interface 4) ...

  9. Ajax Learning notes ( One )

    source :http://www.imooc.com/learn/250 Ajax Not some kind of programming language , It's a technology that can update some pages without reloading the whole page . One . The concept is introduced -- asynchronous utilize XMLHttpR ...

Random recommendation

  1. start-up app Full screen display Default.png

    Always liked it MJ The lecture video of , Today, I read his blog and learned something. I'll record it by the way . By default ,app Show Default.png Time is not real " Full screen display ", Because the status bar at the top is not hidden , For example, below ...

  2. HttpClient I/O exception (java.net.SocketException) caught when processing request: Connect

    from :http://luan.iteye.com/blog/1820054 I/O exception (java.net.SocketException) caught when processin ...

  3. python In interactive mode cp65001 abnormal

    unknown encoding: cp65001 abnormal python Enter the command line interaction mode after installation , Enter any code to report unknown encoding: cp65001 abnormal You need to encode (UTF-8) It is amended as follows Jane ...

  4. Python Automation operation and maintenance 27、Django( One )

    One . summary 1. What is a framework ? frame , namely framework, In particular, it refers to a constrained supporting structure designed to solve an open problem , Using frameworks can help you develop specific systems quickly , In short, it is to use the stage built by others , You do the show . 2. often ...

  5. Problem E: Product

    Problem E: ProductTime Limit: 1 Sec Memory Limit: 128 MBSubmit: 18 Solved: 14[Submit][Status][Web Bo ...

  6. eclipse4.3 install tomcat8

    Go to the WTP downloads page, select the 3.6.0 version , and download the zip (under Traditional Zip ...

  7. bzoj 4653: [Noi2016] Section

    Description On the number axis there is n Closed interval [l1,r1],[l2,r2],...,[ln,rn]. Now we're going to choose from them m Intervals , Make this m Each interval contains at least one location . let me put it another way , That is to make there exist a x ...

  8. SAS︱ Data index 、 Data set common operations (set、where、merge、append)

    Most of the code comes from teacher Yao Zhiyong <SAS Programming and data mining business case >. I always think that climbing mountains is small , can . Every time I come to the starting point , Daniel , Come slowly and share with me ,please~ ------------ ...

  9. Programming In Scala note - Chapter six 、 Functional objects

    This chapter is mainly to define and perfect a rational number class Rational For clues , Analyze and introduce the definition of class , Constructors , Method rewriting , Variable definition and privatization , And the definition of operators . One .Rational Class definitions and constructors 1. Define an empty class ...

  10. Based on Baidu AI Face recognition and speech synthesis on open platform

    Based on Baidu AI Face recognition and speech synthesis Project needs (1) Face recognition stay Web Pictures of people on the interface , The background to use Java Technology receives pictures , Then decode the picture , Call the cloud platform interface to recognize face features , The age of the person who receives the platform return . Gender . Yan ...