/**
* @author Supersha
* @QQ:770104121
*/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Document</title>
<script type="text/javascript">
//注意,編碼要同意為utf-8才能避免中文參數(shù)和返回中文的亂碼問題
function Ajax(prop){
this.action(prop); //在實例化的時候就調(diào)用action方法
}
Ajax.prototype = {
createXHR: function(){ //創(chuàng)建XMLHttpRequest對象
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xhr;
},
action: function(prop){
var xhr = this.createXHR();
if (xhr) {
var url = encodeURI(prop["url"]); //對URL進(jìn)行編碼
if (prop["method"] == "GET" && url && prop["success"]) { //GET方法
xhr.onreadystatechange = function(){
(function(){ //自執(zhí)行函數(shù)用于檢查服務(wù)器的返回狀態(tài)并執(zhí)行回調(diào)函數(shù)
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); //執(zhí)行回調(diào)函數(shù)
}
})();
};
//alert(prop["hander"] instanceof Function);
xhr.open("GET", url, true);
xhr.send(null);
}
else
if (prop["method"] == "POST" && url && prop["success"]) { //POST方法
xhr.onreadystatechange = function(){
(function(){
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); //執(zhí)行回調(diào)函數(shù)
}
})();
};
if (prop["params"]) {
url = url.indexOf("?") > -1 ? url + "&" + prop["params"] : url +"?" + prop["params"];
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(null);
}
}
else
if (!xhr && prop["fail"]) {
prop["fail"]();
}
}
}
function getData(){
var ajax = new Ajax({
url: "test.php",
method: "POST",
success: onComplete,
params: "name="+escape("沙鋒") //進(jìn)行編碼
});
}
function onComplete(obj){
alert(unescape(obj.responseText)); //進(jìn)行轉(zhuǎn)碼
}
</script>
</head>
<body>
<input type="button" value="Get Data" onclick="getData()"/>
</body>
</html>
注釋:
Ajax對象接受一個對象字面量為參數(shù),這個對象字面量中包含method,url,success,params,fail參數(shù)
method:"GET"或者"POST"
url:服務(wù)器端文件路徑
success:當(dāng)請求沒有錯誤的時候,調(diào)用的回調(diào)函數(shù),該回調(diào)函數(shù)帶一個XMLHttpRequest對象的參數(shù)
fail:當(dāng)請求錯誤的時候調(diào)用
params:當(dāng)使用POST方法發(fā)送請求是,params為參數(shù)字符串聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com