给初学ajax的人,

这是原生的ajax,稍稍的封装了下,

对了,option为json格式的数据,对此可先看这个

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
      
/*
调用方式:

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;
}

 

 

 

posted on 2010-05-29 00:32 SingleYW 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/singleyw/archive/2010/05/29/1746752.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值