table of Contents
AJAX introduction
AJAX (Asynchronous JavaScript and XML) means asynchronous JavaScript and XML.
AJAX is not a new programming language, but a technology that allows web pages to be updated asynchronously through a small amount of data exchange with the server in the background without reloading the entire web page. If the traditional web page does not use AJAX, if you need to update the content, you must reload the entire web page. AJAX is based on existing Internet standards.
Google support
In 2005, Google made AJAX popular with its Google Suggest.
Google Suggest uses AJAX to create a highly dynamic web interface: when you enter keywords in the Google search box, JavaScript will send these characters to the server, and the server will return a list of search suggestions.
AJAX basics
XMLHttpRequest
It is the foundation of AJAX.
Steps to send a request using Ajax:
- 1. Create an XMLHttpRequest object
- 2. Send a request to the server
- 3. Perform sending action
- 4. Specify the callback function
XMLHttpRequest object
The XMLHttpRequest object is used to exchange data with the server. All modern browsers support XMLHttpRequest 对象
( IE5
and IE6
use ActiveXObject
) XMLHttpRequest for exchanging data with the server behind the scenes. This means that certain parts of the webpage can be updated without reloading the entire webpage.
Create an XMLHttpRequest object
All browsers (IE7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.
Syntax to create an XMLHttpRequest object:
variable=new XMLHttpRequest();
Note: Internet Explorer (IE5 and IE6) uses ActiveX objects:
variable=new ActiveXObject("Microsoft.XMLHTTP");
Send a request to the server
To send a request to the server, use the open()
and send()
method of the XMLHttpRequest object : The syntax for sending a request is as follows:
xmlhttp.open(method,url,async);
xmlhttp.send(string);
Specify the request type, URL, and whether to process the request asynchronously.
Parameter analysis:
- open()-ready to send
- method: the type of request; GET or POST
- url: the location of the file on the server
- async: The parameter is true (asynchronous) or false (synchronous)
- send()-Send the request to the server.
- string: only used for POST requests
Request method
There are ways request GET
and POST
, compared with POST, GET easier and faster, and can be used in most cases.
//GET请求:
xhr.open('GET','./check.php?username='+uname+'&password='+pw,true);
xmlhttp.send();
POST request
The general use of POST request is:
- Unable to use cache file (update the file or database on the server)
- Send a large amount of data to the server (POST has no data limit)
- When sending user input containing unknown characters, POST is more stable and reliable than GET
If you need to POST data like an HTML form, use setRequestHeader()
to add it HTTP 头
. Then send()
a predetermined method the data to be transmitted:
Add the HTTP header syntax format to the request:
setRequestHeader(header,value)
Parameter analysis:
- header: the name of the request header
- value: the value of the request header
Examples:
//POST请求:
xhr.open('POST','./check.php?username='+uname+'&password='+pw,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username='+uname+'&password='+pw");
Asynchronous True or False
If AJAX XMLHttpRequest object to be used, then that open()
process async
parameters must be set true
:
xhr.open('GET','./check.php?username='+uname+'&password='+pw,true);
xmlhttp.send();
When using async=true, specify the event function to be executed in response to the ready state in the onreadystatechange event:
When async=false, there is no need to write the onreadystatechange function:
Server response
To obtain a response from the server, by using the XMLHttpRequest object responseText
or responseXML
properties:
- responseText gets the response data in string form.
- responseXML obtains the response data in XML format.
onreadystatechange event
When the request is sent to the server, we need to perform some response-based tasks.
Whenever readyState
change triggered onreadystatechange 事件
. Status information
readyState
stored XMLHttpRequest
in the attribute .
The three important attributes of the XMLHttpRequest object are as follows:
Attributes | description |
---|---|
onreadystatechange | Store the function (or function name), which will be called whenever the readyState property changes. |
readyState | The status of XMLHttpRequest is stored. From 0 到 4 change. 0 : The request has not been initialized;: The 1 server connection has been established;: The 2 request has been received;: The 3 request is being processed 4 ;: The request has been completed and the response is ready |
status | 200 : "OK" 404 ;: page not found |
In the onreadystatechange event, we specify the task to be performed when the server response is ready to be processed.
When readyState
equal 4
and the state is 200
, the response indicating ready:
Use callback function
A callback function is a function that is passed to another function as a parameter.
If there are multiple AJAX tasks on the website, you should write a standard function for creating an XMLHttpRequest object and call this function for each AJAX task.
Full example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>初识Ajax开发</title>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById('btn');
btn.onclick = function(){
var uname = document.getElementById('username').value;
var pw = document.getElementById('password').value;
// 1、创建XMLHttpRequest对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//标准
}else{
xhr = new ActiveXObject("Microsoft");//IE5,IE6
}
// readyState=0表示xhr对象创建完成
console.log(xhr.readyState + '----------1-----------');
// 2、准备发送
var param = 'username='+uname+'&password='+pw;
xhr.open('post','04post.php',true);
// 3、执行发送动作
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(param);//post请求参数在这里传递,并且不需要转码
// 4、指定回调函数
// readyState=1表示已经发送了请求
console.log(xhr.readyState + '----------2-----------');
// 该函数调用的条件就是readyState状态发生变化(不包括从0变为1)
xhr.onreadystatechange = function(){
console.log(xhr.readyState + '----------3-----------');
// 4表示服务器返回的数据已经可以使用了,但是这个数据不一定是正常的
if(xhr.readyState == 4){
// 200表示服务器返回的数据是正常的,不是200的话表示数据是错误的
if(xhr.status == 200){
// 这里的200表示数据是正常的
alert(xhr.responseText);
// xhr.responseXML
}
}
}
}
}
</script>
</head>
<body>
<form>
用户名:
<input type="text" name="username" id="username"><span id="info"></span>
<br> 密码:
<input type="text" name="password" id="password">
<input type="button" value="登录" id="btn">
</form>
</body>
</html>