Ajax
1. Course introduction
Static websites and dynamic websites are synchronized, but the synchronization method has disadvantages: page request responsive blocking, affecting the user experience
In order to solve this problem, a partial update of the page (hidden frames) can be achieved through flexible means. Because hidden frames are not convenient, there is Ajax
2. Hidden frames for partial update
<form action="./11inner.php" method="post" target="abc"> 用户名:<input type="text" name="username"> 密 码:<input type="password" name="password"> <input type="submit" value="提交"> </form> <iframe src="" width="200 " height = " 200 " frameborder = " 2 " name = " abc " > </ iframe> Code in PHP <? Php $ uname = $ _POST [ ' username ' ]; $ pw = $ _POST [ ' password ' ] ; if ($ uname == ' 111 ' && $ pw == ' 111 ' ) { // parent in js means parent page echo '<script> parent.document.getElementById ("dv"). innerHTML = "Login successful" </ script> ' ; } else { echo ' <script> parent.document.getElementById ("dv"). innerHTML = "Username Or wrong password "</ script> ' ; } ?>
3. How to implement Ajax response to requests
Basic steps: create XMLHttpRequest object-> configure send parameters-> execute send-> process response
1 , the object creating xhr var xhr = null ; IF (window.XMLHttpRequest) { standard browser xhr = new new the XMLHttpRequest (); } the else { nonstandard browser IE6 / . 7 / . 8 xhr = new new the ActiveXObject ( ' Microsoft.XMLHTTP ' ) ; } readyState == 0 means xhr object initialization is completed console.log (xhr.readyState + ' --------- 1 ---------- ' ); 2. Configure the sending parameter vartype = ' get ' ; var myurl = ' ./data.php ' ; var async = false ; // The default value of the third parameter is true, which means asynchronous; false means synchronous xhr.open (type, myurl, async ); 3 , the transmission var param = null ; xhr.send (param); the readyState == . 1 indicates that the request has been issued 4 , the process response (specify a callback function), the following is not our own callback function to call, and automatically called by the browser so When is the browser called? xhr.readyState ( 0 , 1 , 2 , 3 , 4) When this state value changes, call xhr.onreadystatechange = function () { if (xhr.status == 200 ) { if (xhr.readyState == 4 ) { Get the server response data var result = xhr.responseText; } } } If it is a synchronous request, there is no need to use the callback function, you can get the data directly through xhr.responseText console.log (xhr.responseText);
4. Process the status in the response
(xhr.status == 200)
xhr.status is the status code of the http protocol: 200 success, 404 resource not found, 500 server error
5. The readyState in the processing response is the state value (0,1,2,3,4)
readyState == 0 indicates that xhr object initialization is complete
readyState == 1 means the request has been issued
readyState == 2 indicates that the server-side data has been completely returned
readyState == 3 means data is being parsed
readyState == 4 means the data analysis is complete and ready for use
6. Matters needing attention:
1, xhr object creation requires compatible processing
2. The role of the three parameters of xhr.open
3. xhr.readyState state value to understand
4. Get the server response data through xhr.responseText
5. For get requests, the parameters of xhr.send () are fixed as null
6. The role and difference between xhr.status and xhr.readyState
7. Several ways to prevent form submission
1.return false;
2.e.preventDefault();
3. <input type="submit" value="提交" id="btn">把“submit”换成“button”
8. Manually submit the form
form.submit();
9. Ajax-get submission
Aja's get submission data is to pass parameters through url, and need to encode the parameters
xhr.send (); The method parameter is fixed to null
2. Configure the send function
The encodeURI function encodes the get parameter to prevent garbled characters
var param = encodeURI('?username='+uname+'&password='+pw);
xhr.open('get','./data.php'+param);
3. Send
xhr.send(null);
10. Ajax-post submission
Ajax's post submission method is through xhr.send ();
The parameters passed by the function send data instead of passing data through the url
The post submission method must set the request header
Post submitted data does not need to be encoded
2. Configure the send function
xhr.open('post','./33data.php');
// Set request header information (request header must be set for post submission)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencode');
3. Send
var param = 'username='+uname+'&password='+pw;
xhr.send(param);
11. The difference between post and get
get | post |
2. Configure the send function
The encodeURI function encodes the get parameter to prevent garbled characters
var param = encodeURI('?username='+uname+'&password='+pw);
xhr.open('get','./data.php'+param);
3. Send
xhr.send(null);
|
2. Configure the send function
xhr.open('post','./33data.php');
Set request header information (request header must be set for post submission)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
3. Send
var param = 'username='+uname+'&password='+pw;
xhr.send(param);
|
1. Aja's get submission data is passed parameters through url, and the parameters need to be encoded
2. xhr.send (); the method parameter is fixed to null
|
1. Ajax's post submission method is through xhr.send ();
The parameters passed by the function send data instead of passing data through the url
2. The post submission method must set the request header (xhr.setRequestHeader ('Content-Type', 'application / x-www-form-urlencode');)
3. The data submitted by post does not need to be encoded
|
12. The standard format of url
http://www.baidu.com/a/ac/b?flag=123#abc | scheme://host:port/path?query#fragment |
http----scheme | scheme: communication protocol http https ftp |
www.baidu.com --- host | host: domain name or IP address |
The default port of hidden http is 80 --- port | port: The port browser is hidden |
a/ac/b---path | path: path, the part between the port and the question mark |
# Behind abc ---- fragment | fragment: Anchor hash (hash), role: locate a certain position on the page |
13.encodeURICompontent()和encodeURI()
The encodeURIComponent () method can encode special characters in url
encodeURI () method does not convert special characters
var url = 'http://www.sina.com';
var str = 'http://www.baidu.com?username= 张三 & flag =' + encodeURIComponent (': // ??:');
console.log(encodeURI(str));
console.log(encodeURIComponent(str));
|
14. Parse the XML data returned by the server server var result = xhr.responseXML;
15. Parse the json data returned by the server server var result = xhr.responseText;
14&15
Parse the xml data returned by the server
var result = xhr.responseXML;
|
Parse the json data returned by the server
var result = xhr.responseText;
|
Disadvantages of xml data format:
1. Metadata (data describing data): Metadata takes up more space and is not conducive to network transmission
2. Inconvenient to parse
|
json data format
1. The data consists of key-value pairs
2. Keys and values must be enclosed in double quotes
3. The value type can be: numeric string array object
|
json_encode (); The role of the method: convert the array into a json string
$str = json_encode($arr);
JSON.parse (); Function: convert the string into an object
var str = '{"username":"lisi","age":"12"}';
var obj = JSON.parse(str);
var obj = eval('('+str+')');//也可以实现
eval方法的作用就是把符合js语法 的字符串转成代码并执行
eval('console.log(111)');//输出111
|
|
if(xhr.status == 200 && xhr.readyState == 4){
xml数据格式
var ret = xhr.responseXML;
var books = ret.getElementsByTagName('book');
var tag = '';
for (var i = 0; i < books.length; i++) {
var book = books[i];
var name = book.getElementsByTagName('name')[0].innerHTML;
var author = book.getElementsByTagName('author')[0].innerHTML;
var price = book.getElementsByTagName('price')[0].innerHTML;
var desc = book.getElementsByTagName('desc')[0].innerHTML;
tag += '<ul><li>'+name+'</li><li>'+author+'</li><li>'+price+'</li><li>'+desc+'</li></ul>';
}
var container = document.getElementById('container');
container.innerHTML = tag;
}
|
if(xhr.status == 200 && xhr.readyState == 4){
// 原生Ajax从服务器获取的原始数据是字符串(有可能是json格式的字符串)
var result = xhr.responseText;
// JSON.parse()的作用就是把json形式的字符串转化成对象
result = JSON.parse(result);
console.log(result);
var tag = '';
for (var i = 0; i < result.length; i++) {
var book = result[i];
tag += '<ul><li>'+book.name+'</li><li>'+book.author+'</li><li>'+book.price+'</li><li>'+book.desc+'</li></ul>'
}
var container = document.getElementById('container');
container.innerHTML = tag;
}
|
<?php
header('Content-Type:application/xml; charset=utf-8');
?>
<?xml version='1.0' encoding='utf-8' ?>
<booklist>
<book>
<name>三国演义</name>
<author>罗贯中</author>
<price>20</price>
<desc>一个杀伐纷争的年代</desc>
</book>
</booklist>
|
<?php
$arr = array(
array('name'=>'三国演义','author'=>'罗贯中','price'=>'20','desc'=>'一个杀伐纷争的年代'),
);
json_encode()方法的作用:把数组转化成json字符串
$str = json_encode($arr);
echo $str;
print_r($arr);//也可以实现
?>
|