ajax函数代码,给初学ajax的人 ajax函数代码

/*

调用方式:

1.post方式

var txt = escape(sender.value); //document.getelementbyid("").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("").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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值