国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > AJAX > 正文

Ajax 對象 包含post和get兩種異步傳輸方式

2024-09-01 08:31:43
字體:
來源:轉載
供稿:網友
Ajax對象接受一個對象字面量為參數,這個對象字面量中包含method,url,success,params,fail參數

復制代碼 代碼如下:


/**
* @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才能避免中文參數和返回中文的亂碼問題
function Ajax(prop){
this.action(prop); //在實例化的時候就調用action方法
}
Ajax.prototype = {
createXHR: function(){ //創建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進行編碼
if (prop["method"] == "GET" && url && prop["success"]) { //GET方法
xhr.onreadystatechange = function(){
(function(){ //自執行函數用于檢查服務器的返回狀態并執行回調函數
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); //執行回調函數
}
})();
};
//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); //執行回調函數
}
})();
};
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("沙鋒") //進行編碼
});
}
function onComplete(obj){
alert(unescape(obj.responseText)); //進行轉碼
}
</script>
</head>
<body>
<input type="button" value="Get Data"/>
</body>
</html>


注釋:
Ajax對象接受一個對象字面量為參數,這個對象字面量中包含method,url,success,params,fail參數
method:"GET"或者"POST"
url:服務器端文件路徑
success:當請求沒有錯誤的時候,調用的回調函數,該回調函數帶一個XMLHttpRequest對象的參數
fail:當請求錯誤的時候調用
params:當使用POST方法發送請求是,params為參數字符串
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 泰兴市| 彭州市| 罗江县| 青田县| 上犹县| 彭州市| 始兴县| 铁力市| 金沙县| 东宁县| 浦城县| 什邡市| 工布江达县| 昂仁县| 大洼县| 东至县| 花垣县| 玛曲县| 饶阳县| 嘉善县| 汪清县| 讷河市| 维西| 临洮县| 密云县| 乌鲁木齐县| 潢川县| 安徽省| 水富县| 五大连池市| 扬州市| 苏尼特左旗| 阳曲县| 修武县| 略阳县| 五家渠市| 馆陶县| 仁怀市| 洞口县| 博爱县| 望都县|