復(fù)制代碼 代碼如下:
/**
* @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ù)和返回中文的亂碼問(wèn)題
function Ajax(prop){
this.action(prop); //在實(shí)例化的時(shí)候就調(diào)用action方法
}
Ajax.prototype = {
createXHR: function(){ //創(chuàng)建XMLHttpRequest對(duì)象
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"]); //對(duì)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對(duì)象接受一個(gè)對(duì)象字面量為參數(shù),這個(gè)對(duì)象字面量中包含method,url,success,params,fail參數(shù)
method:"GET"或者"POST"
url:服務(wù)器端文件路徑
success:當(dāng)請(qǐng)求沒(méi)有錯(cuò)誤的時(shí)候,調(diào)用的回調(diào)函數(shù),該回調(diào)函數(shù)帶一個(gè)XMLHttpRequest對(duì)象的參數(shù)
fail:當(dāng)請(qǐng)求錯(cuò)誤的時(shí)候調(diào)用
params:當(dāng)使用POST方法發(fā)送請(qǐng)求是,params為參數(shù)字符串
您可能感興趣的文章:- JQuery中使用ajax傳輸超大數(shù)據(jù)的解決方法
- AJAX 異步傳輸數(shù)據(jù)的問(wèn)題
- Ajax實(shí)現(xiàn)的異步傳輸與驗(yàn)證示例代碼
- Ajax異步傳輸與PHP實(shí)現(xiàn)交互示例
- Ajax同步與異步傳輸?shù)氖纠a
- 利用ThinkPHP內(nèi)置的ThinkAjax實(shí)現(xiàn)異步傳輸技術(shù)的實(shí)現(xiàn)方法
- AJAX在GB2312的中文編碼傳輸 AJAX特殊字符編碼正確方法
- ajax數(shù)據(jù)傳輸方式實(shí)例詳解