使用XmlHttpRequest实现简单Ajax

实现简单的Ajax需要三步走:

1.创建爱你XmlHttpRequest

2.对指定地址进行异步请求

3.绑定回调方法,处理请求结果

定义createXMLHttpRequest创建XmlHttpRequest对象

        var xmlHttp;//定义XmlHttpRequest变量
        function createXMLHttpRequest() {
            //IE5或者IE6老版本浏览器
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
            //新版浏览器
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

定义PointRequest方法(方法仅仅是测试),在方法中调用了创建XmlHttpRequest的方法,onreadystatechange进行绑定回调函数,使用open方法进行请求URL

open方法有三个参数,第一个是请求的方式(可选值为Get和Post),第二个参数为请求的地址,可以传递参数的,地址可以是一个页面也可以是一个webservice,

第三个参数值为bool(true或者false),当设置为true说明会在调用send方法之后继续执行代码(即为异步调用),不会等待服务器的响应,应该指定onreadystatechange事件,

设置为false时候则为同步调用,等待服务器请求

       function PointRequest()//状态请求 
{
//alert('看来已经执行了stateRequest了');
createXMLHttpRequest(); //引用xmlhttp实例
xmlHttp.onreadystatechange = handleStateChange; //在请求状态发生改变时调用此方法
xmlHttp.open("POST", "ping_result.aspx?GetPointData=" + "true", true);
xmlHttp.send(null);
}

function handleStateChange() {
//状态从0变化到4,当为4表示完成
if (xmlHttp.readyState == 4) {
//当状态等于200表示成功
if (xmlHttp.status == 200) {
//成功后执行其他操作
showMapPoints(xmlHttp.responseText);
}
}
}

 protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["GetPointData"]))
            //输出文本,用于在回调函数中使用
Response.Write(Session["mapPointData"].ToString());
}




posted @ 2011-10-12 20:30  wangyafei_it  阅读(218)  评论(0编辑  收藏  举报