DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX基礎知識 >> 給初學ajax的人 ajax函數代碼
給初學ajax的人 ajax函數代碼
編輯:AJAX基礎知識     
復制代碼 代碼如下:
/*
調用方式:
1.POST方式
var txt = escape(sender.value); //document.getElementById("<%= txtName.ClientID %>").value);
var data = "name=" + txt + "&pwd=" + txt;
var option = { "url": "handler/Handler.ashx"
, "action": "POST"
, "callback": function(){
if (xmlHttp.readyState == 4) {//服務器給了回應
if (xmlHttp.status == 200) {//服務正確響應
alert(xmlHttp.responseText);
}
xmlHttp = null; //回收資源
}
   }
, "data": data
};
ajax(option);
2.GET方式
var txt = escape(sender.value); //document.getElementById("<%= txtName.ClientID %>").value);
var option = { "url": "handler/Handler.ashx&name=" + txt + "&pwd=" + txt
, "action": "POST"
, "callback": function(){
if (xmlHttp.readyState == 4) {//服務器給了回應
if (xmlHttp.status == 200) {//服務正確響應
alert(xmlHttp.responseText);
}
xmlHttp = null; //回收資源
}
   }
};
ajax(option);
*/
function ajax(option) {
createXMlHttpRequest(); //創建xmlHttpRequest 對象
if (option != null && option != undefined) {
if (option.url == null && option.url == undefined) {
xmlHttp = null;
alert("缺少必要參數option.url");
return;
}
if (option.action == null && option.action == undefined) {
xmlHttp = null;
alert("缺少必要參數option.action");
return;
}
xmlHttp.open(option.action, option.url, true);
if (option.contentType != null && option.contentType != undefined) {
xmlHttp.setRequestHeader("Content-Type", option.contentType);
} else {
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (option.callback != null && option.callback != undefined) {
xmlHttp.onreadystatechange = option.callback;
}
if (option.action.toUpperCase() == "POST") {
xmlHttp.send(option.data);
} else {
xmlHttp.send(null);
}
}
}
var xmlHttp; //調用完成後最好回收下 xmlHttp = null;
/*獲取元素*/
function g(arg) {
var t = document.getElementById(arg);
if (null != t && t != undefined) {
return t;
}
t = document.getElementsByName(arg);
if (null != t && t != undefined) {
return t;
}
t = document.getElementsByTagName(arg);
if (null != t && t != undefined) {
return t;
}
}
/*創建ajax請求對象*/
function createXMlHttpRequest() {
try {//Firefox, Chrome, Surfri, Opera+8
xmlHttp = new XMLHttpRequest();
}
catch (ie) {
try {//IE6+
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (ie) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved