給初學(xué)ajax的人 ajax函數(shù)代碼
更新時(shí)間:2010年05月31日 20:23:44 作者:
是原生的ajax,稍稍的封裝了下,對了,option為json格式的數(shù)據(jù),對此可先看這個(gè)
復(fù)制代碼 代碼如下:
/*
調(diào)用方式:
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) {//服務(wù)器給了回應(yīng)
if (xmlHttp.status == 200) {//服務(wù)正確響應(yīng)
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) {//服務(wù)器給了回應(yīng)
if (xmlHttp.status == 200) {//服務(wù)正確響應(yīng)
alert(xmlHttp.responseText);
}
xmlHttp = null; //回收資源
}
}
};
ajax(option);
*/
function ajax(option) {
createXMlHttpRequest(); //創(chuàng)建xmlHttpRequest 對象
if (option != null && option != undefined) {
if (option.url == null && option.url == undefined) {
xmlHttp = null;
alert("缺少必要參數(shù)option.url");
return;
}
if (option.action == null && option.action == undefined) {
xmlHttp = null;
alert("缺少必要參數(shù)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; //調(diào)用完成后最好回收下 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;
}
}
/*創(chuàng)建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;
}
相關(guān)文章
解決ajax提交到后臺(tái)數(shù)據(jù)成功但返回不走success而走的error問題
今天小編就為大家分享一篇解決ajax提交到后臺(tái)數(shù)據(jù)成功但返回不走success而走的error問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
AJAX實(shí)現(xiàn)簡單的注冊頁面異步請求實(shí)例代碼
下面小編就為大家?guī)硪黄狝JAX實(shí)現(xiàn)簡單的注冊頁面異步請求實(shí)例代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
配合AJAX天氣預(yù)報(bào)的webService 之a(chǎn)sp
配合AJAX天氣預(yù)報(bào)的webService 之a(chǎn)sp...2007-01-01
分頁技術(shù)原理與實(shí)現(xiàn)之無刷新的Ajax分頁技術(shù)(三)
這篇文章主要介紹了分頁技術(shù)原理與實(shí)現(xiàn)的第三篇:無刷新的Ajax分頁技術(shù),感興趣的小伙伴們可以參考一下2016-06-06

