ajax does not reload the entire web page, update part of the web page technology
Note: ajax only works when it is running on the server. I usually use phpstudy locally
Advantage:
1. Optimize the user experience
2. It undertakes part of the work of the server and reduces the pressure of the server
3. Optimized the transmission of server-side and browser-side, and reduced the bandwidth occupation
Disadvantages:
1. Fallback button not supported
2. Weak support for search engines
3. Security issues, exposing the details of interaction with the server side
XMLHttpRequest object
1. You can make requests to the server and process responses without blocking users
2. Partial content can be updated without updating the entire web page
How to use ajax
1. Create XMLHttpRequest object
2. Create an HTTP request and specify the method and URL (required)
3. Set functions that respond to HTTP request state changes
4, Initiate request
Two ways to create XMLHttpRequest objects: (compatible with browsers)
1. Full version
//Encapsulate browser compatible xhr object function createXhr(){ //IE7+,Other browsers if(typeof XMLHttpRequest!="undefined"){ return new XMLHttpRequest();//Return xhr Instance of object }else if(typeof ActiveXObject!="undefined"){ //IE7 And below //All possible ActiveXObject Edition var arr=["Microsoft.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP.2.0"]; var xhr; //loop for(var i=0,len=arr.length;i<len;i++){ try{ xhr=new ActiveXObject(arr[i]);//Any version supports, you can exit the loop break; }catch(e){ } } return xhr;//Return to created ActiveXObject object }else{ //No support. throw new Error("Your browser does not support XHR Object!"); } }
2. Abridged edition
function createXhr(){ //IE7+,Other browsers if(window.XMLHttpRequest){ return new XMLHttpRequest(); }else{ //IE7 Following return new ActiveXObject("Microsoft.XMLHTTP"); } }
Test whether the creation is successful
//Establish XMLHttpRequest object var xhr=createXhr(); console.log(xhr);
. open(method, url, async) initializes the request and is ready to send (requests can only be sent to URLs that use the same port and protocol in the same domain)
method: get or post (get is faster and simpler, but it can't send a lot of data, can't use cache files, and has no post stability and reliability)
url: required (the location of the file on the server, which can be any type, such as. txt. xml. asp. php)
async: asynchronous, true asynchronous, false synchronous (during synchronization, the browser must wait until the server finishes processing; during asynchronous, the browser can perform other operations before the server finishes processing)
get preparation request adds parameters directly, and post preparation request does not add parameters here
//2,get Create request xhr.open("get","./server/slider.json?user=cyy&age=25",true); //post Create request xhr.open("post","./server/slider.json",true);
Function responding to the state change of XMLHttpRequest object
. onreadystatechange function to detect state changes
. readyState==4 response content parsing completed
. status > = 2 = = & &. Status < 300 asynchronous call succeeded
. status==304 the requested resource has not been modified. You can use the browser's cache
Send request. send()
To send a post request, you need to pass in parameters (in the form of objects). To send a get request, you do not need to pass in null
HTTP header needs to be added for post request
.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
//get Send request xhr.send(null); //post Send request xhr.send({user:"cyy",age:25}); //Set up post Request header xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Get the data returned by the server
The string form of the data returned by the responseText server
DOM compliant document data object (in XML form) for data returned by the responseXML server
Status returned status code (for example, 404 means not found, 200 means ready)
String information of status Text status code
//Get the data returned by the server console.log(xhr.responseText);
View network status
json data format
The full name is a javascript object representation, intended to replace the cumbersome XML format
json can represent three types of values:
1. Simple value
Same as js syntax, it can be string, numeric value, Boolean value, null, but undefined is not supported
String must be in double quotes, not single quotes
Value must be decimal, not NaN and Infinity
2, object
Key names must be enclosed in double quotes
Two properties with the same name should not appear in the same object
3, array
The last member of an array or object, which cannot be followed by a comma
Example: slider.json
{ "code": 0, "slider": [ { "linkUrl": "http://www.baidu.com", "picUrl": "img/cat1.jpg" }, { "linkUrl": "http://www.baidu.com", "picUrl": "img/cat2.jpg" }, { "linkUrl": "http://www.baidu.com", "picUrl": "img/cat3.jpg" }, { "linkUrl": "http://www.baidu.com", "picUrl": "img/cat4.jpg" } ] }
The data returned by. responseText is a string, so it needs to be converted to an object first
Use the. eval() function
//Get the data returned by the server console.log(typeof xhr.responseText);//string //Convert string to object console.log(eval("("+xhr.responseText+")"));
eval("("+xhr.responseText + ")"); means forced conversion to json object, which is written as "eval" ("+ data +")); this format is because json starts and ends in the way of "{}". In JavaScript, it will be treated as a statement block, so it must be forced to convert it into an expression. The purpose of adding parentheses is to force eval function to convert the expression in parentheses into an object instead of executing it as a statement when processing JavaScript code. For example, object literal {}, such as without outer parentheses , eval will recognize braces as the start and end tags of JavaScript code blocks, then {} will be considered as executing an empty statement, so the following two execution results are different:
console.log(eval("{}"));//undefined console.log(eval("({})"));//{}
There are also two methods for json objects:
1. JSON.parse() is used to convert json strings to objects
2. JSON.stringify converts a value to a JSON string
Because eval() can execute code that does not conform to json format and may contain malicious code, it is not recommended to use. parse() instead
data=JSON.parse(xhr.responseText);
console.log(data.slider);
Finally, render the data to the page
Release the file index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <style> *{margin:0;padding:0;} .wrap{width:250px;height:250px;margin:50px auto;overflow:hidden;} .banner{height:250px;width:1000px;} .banner a{width:250px;height:250px;display: block;float: left;} .banner a img{width:250px;height:250px;display: block;} </style> <script src="jquery.js"></script> </head> <body> <div class="wrap"> <div class="banner" id="banner"></div> </div> <script> //Encapsulate browser compatible xhr object function createXhr(){ //IE7+,Other browsers if(typeof XMLHttpRequest!="undefined"){ return new XMLHttpRequest();//Return xhr Instance of object }else if(typeof ActiveXObject!="undefined"){ //IE7 And below //All possible ActiveXObject Edition var arr=["Microsoft.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP.2.0"]; var xhr; //loop for(var i=0,len=arr.length;i<len;i++){ try{ xhr=new ActiveXObject(arr[i]);//Any version supports, you can exit the loop break; }catch(e){ } } return xhr;//Return to created ActiveXObject object }else{ //No support. throw new Error("Your browser does not support XHR Object!"); } } //1,Establish XMLHttpRequest object var xhr=createXhr(),data; //response XMLHttpRequest Function of state change //onreadystatechange Monitoring status change xhr.onreadystatechange=function(){ if(xhr.readyState==4){//Response content parsing completed if((xhr.status>=200&&xhr.status<300)||xhr.status==304){ //xhr.status>=200&&xhr.status<300 Indicates successful transaction //xhr.status==304 Indicates that the cache has not changed, so it can be read from the cache //Get the data returned by the server //console.log(typeof xhr.responseText);//string //Convert string to object data=JSON.parse(xhr.responseText); //console.log(data.slider); //Render data renderData(); } } } //2,get Create request xhr.open("get","./server/slider.json?user=cyy&age=25",true); //get Send request xhr.send(null); //post Create request //xhr.open("post","./server/slider.json",true); //post Send request //xhr.send({user:"cyy",age:25}); //Set up post Request header //xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //Render data function renderData(){ var imgs=data.slider,str=""; var banner=document.getElementById("banner"); for(var i=0,len=imgs.length;i<len;i++){ //console.log(imgs[i]); str+="<a href='"+imgs[i].linkUrl+"'><img src='"+imgs[i].picUrl+"'></a>"; } console.log(str); banner.innerHTML=str; } </script> </body> </html>
Renderings (i.e. simulated access to the broadcast map)
ajax method of jquery:
$.ajax()
$.get()
$.post()
$.getJson()
//jquery Of $.ajax() $.ajax({ url:"./server/slider.json", //Request address type:"post", //Request method, default is get async:true, //Asynchronous synchronization, default is true asynchronous dataType:"json", //Data format returned success:function(data){ //Respond to successful actions JQRenderData(data.slider); //data Is the returned data } }); function JQRenderData(data){ var str=""; $.each(data,function(index,obj){ str+="<a href='"+obj.linkUrl+"'><img src='"+obj.picUrl+"'></a>"; }); $("#banner2").html(str); }
$. Each (obj, function (index, value) {}) method, traversing objects or arrays
Index array index or object property name
Value array item or object property value
Here is the code implemented in two ways: javascript and jqeury
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <style> *{margin:0;padding:0;} .wrap{width:250px;height:250px;margin:50px auto;overflow:hidden;} .banner{height:250px;width:1000px;} .banner a{width:250px;height:250px;display: block;float: left;} .banner a img{width:250px;height:250px;display: block;} </style> <script src="jquery.js"></script> </head> <body> <div class="wrap"> <div class="banner" id="banner"></div> </div> <div class="wrap"> <div class="banner" id="banner2"></div> </div> <script> //Encapsulate browser compatible xhr object function createXhr(){ //IE7+,Other browsers if(typeof XMLHttpRequest!="undefined"){ return new XMLHttpRequest();//Return xhr Instance of object }else if(typeof ActiveXObject!="undefined"){ //IE7 And below //All possible ActiveXObject Edition var arr=["Microsoft.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP.2.0"]; var xhr; //loop for(var i=0,len=arr.length;i<len;i++){ try{ xhr=new ActiveXObject(arr[i]);//Any version supports, you can exit the loop break; }catch(e){ } } return xhr;//Return to created ActiveXObject object }else{ //No support. throw new Error("Your browser does not support XHR Object!"); } } //1,Establish XMLHttpRequest object var xhr=createXhr(),data; //response XMLHttpRequest Function of state change //onreadystatechange Monitoring status change xhr.onreadystatechange=function(){ if(xhr.readyState==4){//Response content parsing completed if((xhr.status>=200&&xhr.status<300)||xhr.status==304){ //xhr.status>=200&&xhr.status<300 Indicates successful transaction //xhr.status==304 Indicates that the cache has not changed, so it can be read from the cache //Get the data returned by the server //console.log(typeof xhr.responseText);//string //Convert string to object data=JSON.parse(xhr.responseText); //console.log(data.slider); //Render data renderData(); } } } //2,get Create request xhr.open("get","./server/slider.json?user=cyy&age=25",true); //get Send request xhr.send(null); //post Create request //xhr.open("post","./server/slider.json",true); //post Send request //xhr.send({user:"cyy",age:25}); //Set up post Request header //xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //Render data function renderData(){ var imgs=data.slider,str=""; var banner=document.getElementById("banner"); for(var i=0,len=imgs.length;i<len;i++){ //console.log(imgs[i]); str+="<a href='"+imgs[i].linkUrl+"'><img src='"+imgs[i].picUrl+"'></a>"; } console.log(str); banner.innerHTML=str; } </script> <script> //jquery Of $.ajax() $.ajax({ url:"./server/slider.json", //Request address type:"post", //Request method, default is get async:true, //Asynchronous synchronization, default is true asynchronous dataType:"json", //Data format returned success:function(data){ //Respond to successful actions JQRenderData(data.slider); //data Is the returned data } }); function JQRenderData(data){ var str=""; $.each(data,function(index,obj){ str+="<a href='"+obj.linkUrl+"'><img src='"+obj.picUrl+"'></a>"; }); $("#banner2").html(str); } </script> </body> </html>
What is cross domain:
Same origin policy: same domain name, protocol and port
Requests that do not conform to the source policy are cross domain
A common cross domain solution: JSONP
json: JSON with padding
Principles of JSONP:
Using XMLHttpRequest to access data in different domains directly is not allowed, but js scripts (such as src or href) in different domains can be introduced into the page
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <script src="jquery.js"></script> </head> <body> <script> /* Package JSONP The browser sends a request to the server: http://www.baidu.com?jsonp=abc Server response request: abc(json Data) */ function myJSONP(url,callback){ if(!url) return;//Without url,Then stop //Store 10 letters in an array var arr=["a","b","c","d","e","f","g","h","i","j"], i1=Math.floor(Math.random()*arr.length),//Randomly generate index i2=Math.floor(Math.random()*arr.length), i3=Math.floor(Math.random()*arr.length), name="mydata"+arr[i1]+arr[i2]+arr[i3];//Randomly generated request function name (property name) cbname="myJSONP."+name;//Must be function name.Request function name //Cross domain url Handle //Pass the request function name as the last parameter if(url.indexOf("?")===-1){ //There were no parameters url+="?jsonp="+cbname;//Parameter name can be customized (here is jsonp) }else{ //Original parameters url+="&jsonp="+cbname; } console.log(url); //Dynamic creation script Label var script=document.createElement("script"); //Define callback function executed by script myJSONP[name]=function(data){ try{ callback && callback(data);//If there is a callback, execute the callback }catch(e){ //Error reporting }finally{ //Because each request generates a function and script Tags, polluting functions in the long run //Therefore, at the end of each time, you need to delete functions and variables delete myJSONP[name]; script.parentNode.removeChild(script); } } script.src=url; document.getElementsByTagName("head")[0].appendChild(script); } //Send cross domain request myJSONP("http://class.imooc.com/api/jsonp",function(data){ console.log(data); }); </script> </body> </html>
Data returned by the page
url demo