AJAX (Asynchronous JavaScript and XML), Asynchronous JavaScript and XML
Note: AJAX is a technology that can realize asynchronous update of web pages, which means that local content of web pages can be updated without repeatedly loading the entire web page
JS native and JQuery implement AJAX asynchronous processing
- JS native
XMLHttpRequest object is the foundation of JS to implement AJAX, which is built in all modern browsers (Chrome, Safari, IE7 +, etc.).
Note: older versions of IE (IE5/IE6) use ActiveXObject objects
Create XMLHttpRequest object
var xhr; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); //Chrome, IE7 +, Safari, etc } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE5,IE6 }
Send request to server
- open(method, url, async) method request type (GET or POST); url request server address; async (true asynchronous, false synchronous)
- send(string) string is only used for POST request parameter passing
Note: to avoid getting cached request results, you need to add a unique ID parameter after the url (using the Math.random() function)
//GET request (parameters are added directly after the url) xhr.open("GET", "get_response.php?code=mycode&t=" + Math.random(), true); xhr.send(); //POST request (parameter added to send() method, HTTP header information needs to be added for xhr object) xhr.open("POST", "post_response.php", true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send("code=mycode");
Get server response status and response data
Response status
- onreadystatechange this function is called whenever the readyState state of an xhr object changes
- readyState records the state of the xhr object (0 request uninitialized; 1 server establishing connection; 2 request received; 3 request processing; 4 request completed)
- Status http status (200 "OK")
Response data
- responseText get response data in string form
- responseXML get response data in XML form
xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { xhr.responseText; } }
Here is the complete JS native AJAX request GET and POST sample code
Front end
<html> <head> <title>js for ajax</title> <script type="text/javascript"> //Create XMLHttpRequest object function getxhr() { var xmlHttp; if(window.XMLHttpRequest) { //Chrome, IE7 +, Safari, etc xmlHttp = new XMLHttpRequest(); } else { //IE5,IE6 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } //GET request function ajax_get() { var xhr1 = getxhr(); xhr1.open("GET","response.php?name=colin&t="+Math.random(),true); xhr1.send(); xhr1.onreadystatechange = function() { if(xhr1.readyState == 4 && xhr1.status == 200) { document.getElementById("res1").innerHTML += xhr1.responseText; } } } //POST request function ajax_post() { var xhr2 = getxhr(); xhr2.open("POST","response.php",true); xhr2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr2.send("name=jason"); xhr2.onreadystatechange = function() { if(xhr2.readyState == 4 && xhr2.status == 200) { document.getElementById("res2").innerHTML += xhr2.responseText; } } } </script> </head> <body> <div id="time"><?php echo date('Y-m-d h:i:s'); ?></div> <div id="res1"></div> <div id="res2"></div> <input type="button" value="ajax_get" οnclick="ajax_get()" /> <input type="button" value="ajax_post" οnclick="ajax_post()" /> </body> </html>
To the back end
<?php if($_GET["name"]) $name = $_GET["name"]; else if($_POST["name"]) $name = $_POST["name"]; echo $name.", Hello"; ?>
→ page display
Note: click the "ajax_get" and "ajax_post" buttons to make a request to the server. The time displayed on the page will not change, which proves that the request process is executed asynchronously and only when the current page is refreshed will the time change
- JQuery
JQuery is a JS library, which encapsulates the AJAX of native JS, making the operation more concise and efficient
GET request
$.get(url, data, function(data, status, xhr), dataType)
POST request
$.post(url, data, function(data, status, xhr), dataType)
Note: request parameter description
GET and POST request instances based on JQuery
Front end
<html> <head> <title>jquery for ajax</title> <!-- Attention introduction JQuery library --> <script type="text/javascript" src="./jquery-1.11.2.min.js" /></script> <script type="text/javascript"> function jq_ajax_get() { var data = '{"name":"zen","age":18}'; $.get("response.php", data, function(data, status, xhr){ //Callback function $("#res1").html(data); / / set the innerHTML value of div }); } function jq_ajax_post() { var data = '{"name":"link","age":23}'; $.post("response.php",data,function(data, status, xhr){ //Callback function $("#res1").html(data); / / set the innerHTML value of div }); } </script> </head> <body> <div><?php echo date('Y-m-d h:i:s'); ?></div> <div id="res1"></div> <div id="res2"></div> <input type="button" value="jq_ajax_get" οnclick="jq_ajax_get()" /> <input type="button" value="jq_ajax_post" οnclick="jq_ajax_post()" /> </body> </html>
To the back end
<?php if($_GET["name"]) $name = $_GET["name"]; else if($_POST["name"]) $name = $_POST["name"]; if($_GET["age"]) $age = $_GET["age"]; else if($_POST["age"]) $age = $_POST["age"]; echo $name.", Hello,Age:".$age; ?>
→ page display
Note: click "JQ? Ajax? Get" and "JQ? Ajax? Post" buttons to request the server through JQuery, and the time of page display will not change, proving that the request process is executed asynchronously, and only the time of refreshing the current page will change
AJAX Request