AJAX - Send a request to the server
To send the request to the server, we need to use the open() method and send( ) method. The
open() method requires three parameters:
The first parameter defines the method used to send the request (GET or POST).
Compared to POST, GET is simpler and faster, and works in most cases.
However, please use POST requests in the following situations:
It is not possible to send large amounts of data to the server using cache files (updating files or databases on the server) (POST has no limit on the amount of data). POST is more stable and reliable than GET when user input contains unknown characters
The second parameter specifies the URL of the server-side script (the file can be any type of file, such as .txt and .xml, or Server script files such as .asp and .php (can perform tasks on the server before sending back a response)).
The third parameter specifies that the request should be processed asynchronously (true (asynchronous) or false (synchronous)).
The send() method sends the request to the server. If we assume that the HTML file and the ASP file are located in the same directory, then the code is like this:
xmlHttp.open("GET","time.asp",true) ;
xmlHttp.send(null);
GET or POST?
Compared to POST, GET is simpler and faster, and works in most cases.
However, please use POST requests in the following situations:
It is not possible to send large amounts of data to the server using cached files (updating files or databases on the server) (POST has no limit on data volume). When user input contains unknown characters, POST is more stable and reliable than GET
A simple GET request:
xmlhttp.open("GET","demo_get.html",true); xmlhttp.send();
You may get cached results.
To avoid this, add a unique ID to the URL:
xmlhttp.open("GET","demo_get.html?t=" + Math.random(),true); xmlhttp.send();
If you wish to send information via the GET method, add information to the URL:
xmlhttp.open("GET","demo_get2.html?fname=Henry&lname=Ford",true); xmlhttp.send();
Complete code:
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true); xmlhttp.send(); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>
A simple POST request:
xmlhttp.open("POST","demo_post.html",true); xmlhttp.send();
If you need to POST data like an HTML form, please use setRequestHeader() to add HTTP headers. Then specify the data you wish to send in the send() method
xmlhttp.open("POST","ajax_test.html",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");
Syntax:
setRequestHeader(header,value) Add HTTP header to the request.
header: specifies the name of the header
value: specifies the value of the header
Full code:
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST","/try/ajax/demo_post2.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford"); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">Request data</button> <div id="myDiv"></div> </body> </html>
url - file on the server
The url parameter of the open() method is the address of the file on the server:
xmlhttp.open("GET","ajax_test.html",true);
The file can be any type of file, such as .txt and .xml, or a server script file, such as .asp and .php (which can perform tasks on the server before sending back a response).
Async - True or False?
AJAX refers to Asynchronous JavaScript and XML (Asynchronous JavaScript and XML).
If the XMLHttpRequest object is to be used for AJAX, the async parameter of its open() method must be set to true:
xmlhttp.open("GET","ajax_test.html" ,true);
For web developers, sending asynchronous requests is a huge improvement. Many tasks performed on the server are quite time consuming. Before AJAX, this could cause the application to hang or stop.
With AJAX, JavaScript does not need to wait for a response from the server. Instead:
Execute other scripts while waiting for the server response. Process the response when the response is ready.
Async=true
When using async=true, please specify the function to be executed when responding to the ready state in the onreadystatechange event:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send();
Async = false
If you need to use async= false, please change the third parameter in the open() method to false:
xmlhttp.open("GET","test1.txt",false);
We do not recommend using async=false, but for some small requests, it is also possible.
Remember that JavaScript will wait until the server response is ready before continuing execution. If the server is busy or slow, the application hangs or stops.
Note: When you use async=false, please do not write the onreadystatechange function - just put the code after the send() statement:
xmlhttp.open("GET","ajax_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Example:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>实例</title> <script> window.onload = function() { var oBtn = document.getElementById('btn'); oBtn.onclick = function() { var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('get','new.php',true); //引入new.php文件 xhr.send(); xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { //alert( xhr.responseText ); 后端传来的格式是一个数组里面很多条json 自己可以测试下 var data = JSON.parse( xhr.responseText ); // 将后台获取的内容转为json类型 每一个json里面有两个键:title和date var oUl = document.getElementById('ul1'); //获取显示新闻列表的节点 var html = ''; for (var i=0; i<data.length; i++) { // 循环所有的json数据,并把每一条添加到列表中 html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>'; } oUl.innerHTML = html; //把内容放在页面里 } else { alert('出错了,Err:' + xhr.status); } } } } } </script> </head> <body> <input type="button" value="按钮" id="btn" /> <ul id="ul1"></ul> </body> </html>
Create a new.php file:
<?php header('content-type:text/html;charset="utf-8"'); error_reporting(0); $news = array( array('title'=>'女总理默克尔滑雪时摔倒 骨盆断裂','date'=>'2014-1-6'), array('title'=>'驻英外交官撰文互称对方国家为"伏地魔"','date'=>'2014-1-6'), array('title'=>'安倍:望与中国领导人会面 中方:你关闭了大门','date'=>'2014-1-6'), array('title'=>'揭秘台湾驻港间谍网运作 湖北宜昌副市长被查','date'=>'2014-1-6'), array('title'=>':嫦娥三号是货真价实的中国创造','date'=>'2014-1-6'), ); echo json_encode($news); ?>