AJAX(Asynchronous JavaScript and XML) , 異步的JavaScript和XML
注:AJAX是一種可以實現網頁異步更新的技術,這意味着可以在不重複加載整個網頁的情況下,對網頁局部內容進行更新
JS原生和JQuery實現AJAX異步處理
- JS原生
XMLHttpRequest對象是JS實現AJAX的基礎,所有現代瀏覽器(Chrome、Safarii、IE7+等)均內建有該對象。
注:老版本的IE(IE5/IE6)使用ActiveXObject對象
創建XMLHttpRequest對象
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest(); //Chrome、IE7+、Safari等
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE5、IE6
}
向服務器發送請求
- open(method, url, async) method 請求類型(GET或POST);url 請求的服務器地址;async (true異步,false同步)
- send(string) string 僅用於POST請求傳參
注:GET請求時,爲避免得到緩存的請求結果,需要在url後添加一個唯一ID參數(使用Math.random()函數)
//GET請求(參數直接添加在url後面)
xhr.open("GET", "response.php?code=mycode&t=" + Math.random(), true);
xhr.send();
//POST請求(參數添加到send()方法中,需要爲xhr對象添加HTTP頭信息)
xhr.open("POST", "response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("code=mycode");
獲取服務器響應狀態及響應數據
響應狀態
- onreadystatechange 每當xhr對象的readyState狀態改變時,會調用該函數
- readyState 記錄xhr對象的狀態(0請求未初始化; 1服務器建立連接;2請求已接收;3請求處理中;4請求完成)
- status http狀態(200 “OK”)
響應數據
- responseText 獲取字符串形式的響應數據
- responseXML 獲取XML形式的響應數據
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
xhr.responseText;
}
}
下面是完整的JS原生實現AJAX請求GET和POST示例代碼(後端使用PHP)
→前端
<html>
<head>
<title>js for ajax</title>
<script type="text/javascript">
//創建XMLHttpRequest對象
function getxhr()
{
var xmlHttp;
if(window.XMLHttpRequest)
{
//Chrome、IE7+、Safari等
xmlHttp = new XMLHttpRequest();
}
else
{
//IE5、IE6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
//GET請求
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請求
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>
→後端
<?php
if($_GET["name"])
$name = $_GET["name"];
else if($_POST["name"])
$name = $_POST["name"];
echo $name.", 你好";
?>
→頁面顯示
注:點擊“ajax_get”和“ajax_post”按鈕,對服務器進行請求,頁面顯示的時間不會改變,證明請求過程是異步執行的,只有刷新當前頁面時間纔會改變
- JQuery
JQuery是一個JS庫,其中對原生JS的AJAX進行了封裝,使得操作更加簡潔、高效,下面介紹基於JQuery的幾個主要AJAX函數
GET請求函數
$.get(url, data, function(data, status, xhr), dataType)
POST請求函數
$.post(url, data, function(data, status, xhr), dataType)
注:請求參數描述,其中data爲發送至服務器的請求數據,可以是json或key=value形式(建議json格式);function爲回調函數,額外參數data、status、xhr分別爲服務器返回的數據數據、請求狀態和XMLHttpRequest對象
AJAX請求函數
$.ajax({name:value, name:value, ... })
請求參數描述如下,常用參數有url、data(請求數據:常用json格式)、async(true異步,false同步)、type(請求類型:GET/POST)、dataType(服務器返回數據類型:常用text和json)、success、error等
基於JQuery的GET、POST和AJAX函數請求實例(後端使用PHP)
→前端
<html>
<head>
<title>jquery for ajax</title>
<!-- 注意引入JQuery庫 -->
<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){ //回調函數
$("#res1").html(data); //將請求返回的結果設置爲div的innerHTML值
},"json");
}
function jq_ajax_post()
{
var data = '{"name":"link","age":23}'; //設置請求數據
$.post("response.php",data,function(data, status, xhr){ //回調函數
$("#res1").html(data); //將請求返回的結果設置爲div的innerHTML值
},"json");
}
function jq_ajax()
{
$.ajax({
url:"response.php",
data:{"name":"bob","age":37},
async:true,
type:"GET",
dataType:"text",
success:function(result,status,xhr){
$('#res3').html(result);
},
error:function(xhr,status,error){
$('#res3').html(error);
}
});
}
</script>
</head>
<body>
<div><?php echo date('Y-m-d h:i:s'); ?></div>
<div id="res1"></div>
<div id="res2"></div>
<div id="res3"></div>
<input type="button" value="jq_ajax_get" οnclick="jq_ajax_get()" />
<input type="button" value="jq_ajax_post" οnclick="jq_ajax_post()" />
<input type="button" value="jq_ajax" οnclick="jq_ajax()" />
</body>
</html>
→後端
<?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.", 你好,年齡:".$age;
?>
→頁面顯示
注:點擊“jq_ajax_get”、“jq_ajax_post”和“jq_ajax”按鈕,通過JQuery對服務器進行請求,頁面顯示的時間不會改變,證明請求過程是異步執行的,只有刷新當前頁面時間纔會改變