初学ajax总结

  所谓AJAX就是(Asynchronous JavaScript and XML)异步的javascript和xml,首先说下我感觉没有ajax的话我们所遇到的问题,比如在我们看某个视频的时候,看下面的评价,当我们点击下一页的时候就是出现一个情况:我们的视频会重新开始!所以ajax在某些方面是必须的!

  下面进入正题,我们通常会使用'一般处理页'来处理ajax(*.ashx)在客户端用javascript来处理需要传入服务器端或者从服务器端传过来的数据(这是我的理解)下面我自己写的一个很不错的ajax模型:在一般处理页中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebApplication1
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    [WebService(Namespace="http://tempuri.org/")]
//一个webservice的引用为了在下面使用datatime
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//获取web服务互操作性(wsi)的规范
    public class Handler : IHttpHandler
    {
       
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(DateTime.Now.ToString());
            //把write()里面的数据传入客户端
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

下面是客户端的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function butclick() {
            var httprequest = null;
            // 初始化XMLHttpRequest对象
            if (window.XMLHttpRequest) {
                // Firefox等现代浏览器中的XMLHttpRequest对象创建
                httprequest = new XMLHttpRequest();
            }
            else if (window.ActiveXObject) {
                // IE中的XMLHttpRequest对象创建
                httprequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (!httprequest) {
                alert("创建httprequest对象出现异常!");
            }
            httprequest.open("POST", "Handler.ashx", true);
            //httprequest向handler发送post请求,最后参数是设定是否为异步请求,true为异步,false为同步
            httprequest.onreadystatechange = function () {
                //指定onreadystatechange事件句柄对应的函数
                if (httprequest.readyState == 4) {
                    //4代表服务器返回完成
                    if (httprequest.status == 200) {
                        //200代表成功了
                        document.getElementById("text1").value = httprequest.responseText;
                        //responsetext表示服务器返回的文本,还有一种方式是responseXML是为了获取服务器返回的xml
                    }
                    else {
                        alert("AJAX服务器返回错误!");
                    }
                }
            }
            httprequest.send();
            //在这里才真正的向服务器端发送请求
        }
    </script>
</head>
<body>
    <input id="text1" type="text" />
    <input id="Button1" type="button" value="button" onclick="butclick()" />
</body>
</html>

运行结果:

 

在代码里面都有注释,希望和我一样的初学者能看懂,还有就是如果你看过有什么指教的话,留言。不胜感激!

posted on 2012-05-06 14:16  小茶喏  阅读(1098)  评论(0编辑  收藏  举报

导航