Ajax学习笔记——创建异步对象

 1 //根据不同的浏览器使用相应的方式来创建异步对象
 2 function createXmlHttp(){
 3     xhobj = false;
 4     try{
 5         xhobj = new ActiveXObject("Msxml2.XMLHTTP");//iemsxml3.0+
 6     }
 7     catch(e){
 8         try{
 9             xhobj = new ActiveXObject("Microsoft.XMLHTTP");//iemsxml2.6
10         }catch(e2){
11             xhobj = false;
12         }
13     }
14     if(!xhobj && typeof XMLHttpRequest !='undefined'){
15         //Firefox,Opera 8.0+,Safari,谷歌浏览器等等
16         xhobj = new XMLHttpRequest();
17     }
18     return xhobj;
19 }

  

//使用Get方式
function
GetData(){ var xhr;

xhr
= createXmlHttp();//创建异步对象 xhr.open("GET","FirstAjaxForFun.ashx",true);//设置请求参数 xhr.setRequestHeader("If-Modified-Since","0");//设置浏览器不使用缓存 xhr.onreadystatechange = function(){//设置回调函数(用来检查服务器是否响应) if(xhr.readyState==4&&xhr.status==200){ alert(xhr.responseText);//获得服务器响应数据 } } xhr.send(null);//发送请求,get用Null }
//使用Post方式,天然无缓存
function
PostData(){ var xhr; xhr = createXmlHttp();//创建异步对象 xhr.open("Post","FirstAjaxForFun.ashx",true);//设置请求参数 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function(){//设置回调函数(用来检查服务器是否响应) if(xhr.readyState==4&&xhr.status==200){ alert(xhr.responseText);//获得服务器响应数据 } } xhr.send("txtName=james&txtPwd=1");//发送请求l }

 中文用encodeURI转换,传到后台时,用Microsoft.JScript.GlobalObject.decodeURI转换回来保存到数据库中。

 

posted on 2012-07-19 23:02  非零  阅读(597)  评论(0编辑  收藏  举报