AJAX-AJAX 工具對象
AJAX 工具對象
ajax.js
//ajax工具對象:1.兼容問題 2.便捷問題
function Ajax(){
//1.兼容問題 xhr對象
var xhr = null;
if(window.XMLHttpRequest){//檢測是否有XMLHttpRequest構造方法
//使用XMLHttpRequest構造方法創建xhr對象
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){//檢測是否可以使用低版本ie的ActiveXObject
//使用ActiveXObject來創建xhr對象
//下面的數組爲ie可能使用的版本名稱
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
//遍歷數組測試是否可以使用
for(var i=0;i<versions.length;i++){
//嘗試創建
xhr = new ActiveXObject(versions[i]);
//檢測是否創建成功
if (xhr){
break;
}
}
}else{//都無法使用,就不能用ajax
return false;
}
//繼續簡化ajax第四步
function checkAndUse(func){
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status == 200){
//使用響應的數據
func(xhr.responseText)
}
}
}
}
//定義一個get請求的內部函數
function ajaxGET(url,callback){
//1.創建xhr對象(已經在兼容性位置解決)
//2.建立連接
xhr.open('get',url);
//3.發送數據
xhr.send(null);
//4.檢測請求與響應
checkAndUse(callback);
}
//定義一個post請求的內部函數
function ajaxPOST(url,data,callback){
//1.創建xhr對象(已經在兼容性位置解決)
//2.建立連接
xhr.open('post',url);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//3.發送數據
xhr.send(data);
//4.檢測請求與響應
checkAndUse(callback);
}
//返回值-2.便捷問題 (閉包實例)
return {
//ajax的功能對象
get:ajaxGET,//實現ajax的get異步傳輸
post:ajaxPOST//實現ajax的post異步傳輸
}
}
一:使用 POST 請求
post.php
<?php
//輸出post請求
echo $_POST['age'];
echo "你好啊"
?>
post.html
<!doctype html>
<html>
<head>
<title>使用ajax工具對象</title>
<meta charset="utf-8">
<!--引入js文件-->
<script src="./ajax.js"></script>
</head>
<body>
<button id="btn">檢測工具</button>
</body>
</html>
<script>
//添加事件
btn.onclick=function(){
//使用ajax請求服務器數據
Ajax().post('post.php','age=455',console.log)
}
</script>
二:使用 GET 請求
get.php
<?php
//輸出get請求
echo $_GET['age'];
echo "你好啊"
?>
get.html
<!doctype html>
<html>
<head>
<title>使用ajax工具對象</title>
<meta charset="utf-8">
<!--引入js文件-->
<script src="./ajax.js"></script>
</head>
<body>
<button id="btn">檢測工具</button>
</body>
</html>
<script>
//添加事件
btn.onclick=function(){
//使用ajax請求服務器數據
Ajax().get('post.php?age=455',console.log)
}
</script>