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

首頁 > 開發 > AJAX > 正文

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

2024-09-01 08:29:24
字體:
來源:轉載
供稿:網友
代碼如下:
/**
* @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" onclick="getData()"/>
</body>
</html>

注釋:
Ajax對象接受一個對象字面量為參數,這個對象字面量中包含method,url,success,params,fail參數
method:"GET"或者"POST"
url:服務器端文件路徑
success:當請求沒有錯誤的時候,調用的回調函數,該回調函數帶一個XMLHttpRequest對象的參數
fail:當請求錯誤的時候調用
params:當使用POST方法發送請求是,params為參數字符串
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安康市| 达日县| 江北区| 蓝山县| 湖口县| 合山市| 澎湖县| 松原市| 威信县| 阜新| 砀山县| 若尔盖县| 加查县| 娱乐| 客服| 噶尔县| 沈丘县| 吉木萨尔县| 连平县| 琼中| 宁海县| 青海省| 三门县| 蕉岭县| 马山县| 衡南县| 翁源县| 龙川县| 揭西县| 江源县| 潮州市| 新巴尔虎左旗| 青海省| 达拉特旗| 浮山县| 寿光市| 广河县| 隆尧县| 泽库县| 万山特区| 邛崃市|