欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

给初学ajax的人 ajax函数代码

程序员文章站 2022-06-24 16:22:35
复制代码 代码如下:/* 调用方式: 1.post方式 var txt = escape(sender.value); //document.getelementbyid(...
复制代码 代码如下:

/*
调用方式:
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;
}