2012年10月18日星期四

AJAX无刷新测试

AJAX无刷新测试

HTML代码:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">    <style type="text/css">        #button1        {            width: 95px;        }        #TextArea1        {            width: 555px;            height: 203px;        }        #commentul        {            list-style-type:none;        }        .commentli        {            margin-top:20px;        }        #pageul        {            list-style-type:none;        }        .pageli        {            width:20px;            float:left;        }    </style>    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    <script src="js/Calendar5.js" type="text/javascript"></script>    <script language="javascript" type="text/javascript">        function ajaxtext(url, dom) {            var = "";            if (window.ActiveXObject) { //判断游览器,不同游览器声明的AJAX对象不一样。                = new ActiveXObject("Microsoft.");            }            else if (window.= new else {                alert("错误的游览器~");                return false;            }            //请求地址            "post", url[0] + "?" + url[1] + "=" + url[2], false);           //alert(url[0] + "?" + url[1] + "=" + url[2]);            = function () {                if (== 4) {                     if (== 200) { //请求成功                        //判定请求DOM                        if (dom == "commentul") { //无刷新评论                            var con = var com = con.split("#");                            var data = "";                            for (i = 0; i < com.length - 1; i++) {                                var content = com[i].split("|");                                data += "<li class=commentli><ul><li>" + parseInt(i + 1) + "楼</li><li>发表时间:" + content[0] + "</li><li>IP地址:" + content[1] + "</li><li>内容:" + content[2] + "</li></ul></li>";                            }                            document.getElementById(dom).innerHTML = data;                        }                        else if (dom == "contentul") { //Json传值,无刷新展示数据。                            var datas = $.parseJSON(var con = "";                            for (i = 0; i < datas.length; i++) {                                var data = datas[i];                                con += "<li>编号:" + data.no + "  款号:" + data.id + "  时间:" + data.date + "  价格:" + data.amount + "   <a href='' id='" + data.no + "' onclick='aclick_del(this);return false'>删除</a></li>";                            }                            document.getElementById(dom).innerHTML = con;                        }                        else if (dom == "pageul") { //无刷新分页                            var num = var data = "";                            for (i = 1; i <= num; i++) {                                data += "<li class=pageli><a href='" + i + "'onclick='aclick(this);return false'>" + i + "</a></li>";                            }                            document.getElementById(dom).innerHTML = data;                        }                        else if (dom == "del") {                         }                        else {                            document.getElementById(dom).value = else {                        alert("请求错误~");                    }                }            }            var num = 1;//当前页数        var c = new Calendar("c");        document.write(c);//日历        function button1_onclick() {            ajaxtext(["AJAXrequest.ashx","xx",new Date()],"text1");//无刷新请求当前服务器时间        }        function textblur_blur(val) {            if (val != "") {              ajaxtext(["AJAXrequest.ashx", "id", val], "textcontent");//文本框AJAX            }        }        function select_onchange(val) {            ajaxtext(["AJAXrequest.ashx", "id", val], "textcontent");  //下拉框AJAX        }         function aclick(e) {            ajaxtext(["ajajpage.ashx", "num", $(e).text()], "contentul"); //分页ul            num = $(e).text();        }        function aclick_del(e) {            ajaxtext(["ajajpage.ashx", "del", e.getAttribute("id")], "contentul"); //删除数据            ajaxtext(["ajajpage.ashx", "num", num], "contentul"); //刷新内容            return false;        }        //WCF服务        function AJAX_btn() {            AJAXService.GetPerson(1, function (data) { alert(data.name); }, function () { alert("失败~"); });        }        function btn_insert() {            var no = $("#Textno").val();            var id = $("#Textid").val();            var date = $("#Textdate").val();            var amount = $("#Textamount").val();            if (no != "" && id != "" && date != "" && amount != "") {                date += " 00:00:00";                //WCF插入数据                AJAXService.Insert(no, id, date, amount, function (data) { alert("成功"); }, function () { alert("失败~"); });                $("#Textno").val("");                $("#Textid").val("");                $("#Textdate").val("");                $("#Textamount").val("");            }            else {                alert("请输入完整信息");            }        }    </script></asp:Content><asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">    <span>服务器控件刷新时间</span>    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button2"         runat="server" Text="Button" onclick="Button2_Click" />    <span>客户端AJAX刷新时间</span><input type='text' id='text1' /><input type="button" id='button1' value='确认' onclick="return button1_onclick()" /><br />    <!--  DropDownList ObjectDataSource -->    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"         OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataByID"         TypeName="AJAXtest.DataSetajaxTableAdapters.WarehouseTableAdapter">    </asp:ObjectDataSource>    <br />    <span>客户端离开焦点事件获取值</span><input type="text" id="textblur" onblur="textblur_blur(this.value)" /><asp:DropDownList ID="DropDownList1"    runat="server" DataSourceID="ObjectDataSource1" DataTextField="Warehouse_No"         DataValueField="Warehouse_No" onchange="select_onchange(this.value)">    </asp:DropDownList>    <input type="text" id="textcontent" />&nbsp;    <br />    <!-- WCF ScriptManager -->    <asp:ScriptManager ID="ScriptManager1" runat="server">        <Services>            <asp:ServiceReference Path="~/AJAXService.svc" />        </Services>    </asp:ScriptManager>    <input id="Button4" type="button" value="AJAX WCF"  onclick="AJAX_btn()"/><br />    <ul id="contentul"></ul>    <table><tr><td>编号:<input id="Textno" type="text" /></td><td>款号:<input id="Textid" type="text" /></td>        <td>日期:<input id="Textdate" type="text" onfocus="c.showMoreDay = false; c.show(this);"/></td><td>价格:<input id="Textamount" type="text" /></td>        <td><input type="button" id="bottoninsert" value="增加" onclick="btn_insert()"/></td>           </tr></table>    <br />    <ul id="pageul"></ul>     <script type="text/javascript">         ajaxtext(["ajajpage.ashx", "num", "1"], "contentul"); //显示第一页数据         ajaxtext(["ajajpage.ashx", "action", "pagecount"], "pageul");//显示分页    </script></asp:Content>

AJAXrequest.ashx代码:

public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string id = context.Request["id"];            if (id == null)            {                context.Response.Write(DateTime.Now.ToLongTimeString());//当前时间            }            else            {                var data = new WarehouseTableAdapter().GetData(id); //获取当前编号仓库name                if (data.Count <= 0)                {                    context.Response.Write("没有这个仓库");                }                else                {                    context.Response.Write(data.Rows[0][1].ToString());                }            }        }

ajaxpage.ashx代码:

public class ajajpage : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string action = context.Request["action"]; //分页            string num = context.Request["num"]; //第几页            string del = context.Request["del"]; //删除数据            if (num != null) //当前页面数据            {                int inum = Convert.ToInt32(num);                //强类型Dataset                //select * from (SELECT Charge_No, Customer_ID, Charge_Date, Amount,row_number() over(order by charge_no)num FROM Charges)t                //where num>=@rowstratindex and num<=@rowendindex                var data = new ChargesTableAdapter().GetData(((inum - 1) * 10 + 1).ToString(), (inum * 10).ToString());                List<Data> list = new List<Data>();                foreach (var row in data)                {                    list.Add(new Data() { no = row.Charge_No, id = row.Customer_ID.Trim(), date = row.Charge_Date.ToShortDateString(), amount = row.Amount.ToString() });                }                JavaScriptSerializer jss = new JavaScriptSerializer(); //Json 传数据。                context.Response.Write(jss.Serialize(list));            }            else if (action == "pagecount") //分页            {                var count = new ChargesTableAdapter().SelectCount();                int icount = Convert.ToInt32(count);                int inum = icount / 10;                if (icount % 10 != 0)                {                    inum++;                }                context.Response.Write(inum.ToString());            }            else if (del != string.Empty)             {                if (new ChargesTableAdapter().Delete1(del) > 0) //删除                {                    context.Response.Write("ok");                }                else                {                    context.Response.Write("no");                }            }                   }        public bool IsReusable        {            get            {                return false;            }        }        public class Data        {            public string no{get;set;}            public string id{get;set;}            public string date{get;set;}            public string amount{get;set;}        }    }

AJAXService.svc代码:

 public class AJAXService    {        [OperationContract]        public void DoWork()        {            // 在此处添加操作实现            return;        }         [OperationContract]         public Person GetPerson(int id)        {            return new Person { age = "10", name = "lidy" };        }         [OperationContract]        public bool Insert(string no,string id,string date,string amount)         {             DateTime dt = DateTime.Parse(date);          //强类型DateSet             if (new ChargesTableAdapter().Insert1(no, id, dt, amount) > 0)             {                 return true;             }             return false;         }        public class Person        {            public string name { get; set; }            public string age { get; set; }        }    }

TAG: