About sending asynchronous requests to the server using native Javascript.
Preparatory work:
The Code authoring tool uses a local Apache server that is Wamp with the sublime service, primarily for returning data for easy testing
Steps:
Browser-side
HTML Tag binding event sends Ajax request---->
Five-step operation: 1 Create asynchronous Object xmlhttprequest;
2 Setting the method URL
3 Sending a request to the server
4 Registering events
5 Gets the data returned by the server in the event and Operates.
Server-side
1 Getting request data
2 returning results to the browser
Here's a little demo1 to do a simple request action click the button to send the request to the server side, return the picture address, render the Div's background image
Nobibi on the Code
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <style>4 . Div1{5 width:200px;6 Height:200px;7 Border:1px solid Red;8 margin:20px Auto;9 }Ten . Div2{ one width:300px; a Height:100px; - Border:1px solid Red; - margin:20px Auto; the } - Body{ - text-align:Center; - } + </style> - <Head> + <MetaCharSet= "utf-8"> a </Head> at <Body> - <Divclass= ' Div1 '></Div> - <Divclass= ' Div2 '></Div> - <inputtype= "button"value= "baby"class= ' starbtn '> - <inputtype= "button"value= "hxm"class= ' starbtn '> - <inputtype= "button"value= "lh"class= ' starbtn '> in </Body> - </HTML> to <Script> + //Get button list - varbtnlist=Document.queryselectorall ('. Starbtn'); the //loop-binding Point -and-click Events * for (varI= 0; I<btnlist.length; i++) { $ Btnlist[i].onclick= function(){Panax Notoginseng //new Asynchronous Processing object - varAjax= NewXMLHttpRequest (); the //set the request type to post and the requested page is server1.php + Ajax.open ('Post','server1.php'); a //because it is a post request, you must add setRequestHeader (get request can be ignored) the Ajax.setrequestheader ('Content-type','application/x-www-form-urlencoded'); + //the parameter Name=this.value with the request - Ajax.send ('name='+ this. value); $ //Binding onreadystatechange Events $ Ajax.onreadystatechange=function(){ - //determine if the requested State is successful - if(ajax.readystate==4&&Ajax.status== $) { the //manipulate DOM elements based on return value Ajax.responsetext to change the background picture of a div - Document.queryselector ('. Div1'). Style.background= 'URL ('+Ajax.responsetext+') no-repeat Center/cover';Wuyi Document.queryselector ('. Div2'). InnerHTML=Ajax.responsetext the }; - } wu } - }; about $ </Script>
End of Browser-side Code.
The following is the Service-side code, the server is written in PHP simple sentence
<?PHP//get the data for a POST request $key=$_post[' name ']; //Relational Arrays $STARARR=Array( ' Baby ' = ' images/baby.jpg ', ' hxm ' = ' images/hxm.jpg ', ' lh ' = ' images/lh.jpg ' ); $value=$STARARR[$key];//return picture Address Echo $value; ?>
This completes a simple asynchronous request written using native Javascript.
Send AJAX requests using native JavaScript