当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 给初学ajax的人 ajax函数代码

给初学ajax的人 ajax函数代码

2017年12月12日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网