.NET運用AJAX 總結及其實例


1、AJAX簡介

     (1、沒有AJAX會怎么樣?普通的ASP.Net每次執行服務端方法的時候都要刷新當前頁面,比如實現顯示服務器的時間。每次都要刷新頁面的壞處:頁面刷新打斷用戶操作、速度慢、增加服務器的流量壓力。如果沒有AJAX,在youku看視頻的過程中如果點擊了“頂、踩”、評論、評論翻頁,頁面就會刷新,視頻就會被打斷。試想一個效果:在YOUKU網看視頻,然后看到一個頂踩的功能,看沒有ajax會打斷視頻,然后將按鈕用UpdatePanel包起來就不會打斷視頻了。用HttpWatch看沒有AJAX的時候服務器返回的是整個頁面,有了AJAX服務器只返回幾個按鈕的內容。

   (2、AJAX( AsynchronousJavaScript and XML,異步JavaScript和XML)是一種進行 頁面局部異步刷新的技術。用AJAX向服務器發送請求和獲得服務器返回的數據並且更新到界面中,不是整個頁面刷新,而是 在HTML頁面中使用JavaScript創建XMLHTTPRequest對象來向服務器發出請求以及獲得返回的數據,就像JavaScript版的 WebClient一樣,在頁面中 XMLHTTP Request 來發出 Http 請求和獲得服務器的返回數據,這樣頁面就不會刷新了。 XMLHTTPRequest是AJAX的核心對象
 
2、  XMLHTTPRequest

    (1、開發一個AJAX功能需要 開發服務端和客戶端兩塊程序。以一個顯示服務端時間為例。首先開發一個GetDate1.ashx,輸出當前時間。在HTML頁面中放一個按 鈕,在按鈕的onclick中創建XMLHTTP向GetDate1.ashx發送請求,獲得返回的數據並且顯示到界面上。下面的代碼非常重要,是精華來着,必背:
javascript代碼
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>AJAX01</title>
 5     <script type="text/javascript">
 6         function btnClick() {
 7             //alert(1);
 8             // 1 創建XMLHTTP對象,相當於WebClient
 9             var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
10             
11             if (!xmlhttp) {
12                 alert("創建xmlhttp對象異常");
13                 return;
14             }
15             
16             // 2 “准備”01AJAX.ashx發出Post請求。這里還沒有發出請求
17             //XMLHTTP默認(也推薦)不是同步請求的,也就是open方法並不像WebClient的DownloadString
18             //那樣把服務器返回的數據拿到才返回,
19             //是異步的,因此需要監聽onreadystatechange事件
20 
21 
22             xmlhttp.open("POST", "01AJAX.ashx?id=" + encodeURI('AJAX服務器') + "&ts=" + new Date(), false);
23             
24             xmlhttp.onreadystatechange = function () {
25                 if (xmlhttp.readyState == 4) {//readyState == 4 表示服務器返回數據了
26                     if (xmlhttp.status == 200) {//如果狀態碼為200則是成功
27                         //接收服務器的返回數據,沒有用send的返回值,而是在onreadystatechange事件里來接收
28                         document.getElementById("txtTime").value = xmlhttp.responseText; //responseText屬性為服務器返回的文本
29                     }
30                     else {
31                         alert("AJAX服務器返回錯誤!");
32                     }
33                 }
34             }
35             //不要以為if(xmlhttp.readyState == 4) 在send之前執行!!!!
36             //if (xmlhttp.readyState == 4)只有在服務器返回值以后才會執行,而!!send之后過一會兒服務器才會返回數據
37             xmlhttp.send(); //這時才開始發送請求
38         }
39     </script>
40 </head>
41 <body>
42     <input type="text" id="txtTime" />
43     <input type="button" id="btn" value="button" onclick="btnClick()" />
44 </body>
45 </html>
ashx代碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace AJAX
 7 {
 8     /// <summary>
 9     /// _01AJAx 的摘要說明
10     /// </summary>
11     public class _01AJAx : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             string id = context.Request["id"];
18             context.Response.Write(DateTime.Now.ToString()+"---"+id);
19         }
20 
21         public bool IsReusable
22         {
23             get
24             {
25                 return false;
26             }
27         }
28     }
29 }

 

   (2、不使用UpdatePanel、JQuery等AJAX庫編寫一個AJAX程序。 也可以在xmlhttp.open中向服務器傳遞參數:
xmlhttp.open("POST","GetDate1.ashx?id=1&name="+"encodeURL('中國')", false),如果傳遞給服務器的請求里有中文,則需要使用Javascript函數encodeURI來進行URL編碼。
 
          (3、 發出請求后不等服務器返回數據,就繼續向下執行,所以不會阻塞,界面就不卡了,這就是AJAX中“A”的含義“異步”。只有在服務器返回值以后才會執
       行,而!! send之后過一會兒服務器才會返回數據。
          (4、 xmlhttp.open(" GET","GetDate1.ashx?id=1&name="+"encodeURL('中國')", false),如果這樣單純滴傳兩個靜態參數的話,瀏覽器可能會保持一
       種提取緩存的狀態,所以最好傳一個動態參數,隨意一個參數。這是一個AJAX緩沖存在的問題。如果用POST的方式,就不會發生緩沖的問題。
 案例1:無刷新異步操作-->匯率轉換
html代碼
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>02 huilv question</title>
 5     <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
 6     <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
 7     <script type="text/javascript">
 8         function btnOnclick() {
 9             var moneyType = $("#selectedID").val();
10             var account = $("#myaccount").val();
11             //alert(account);
12             //alert(moneyType);
13             var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
14             if (!xmlhttp) {
15                 alert("error from create xmlhttp!");
16                 return;
17             }
18             xmlhttp.open("POST", "02" + encodeURI('匯率問題') + ".ashx?moneyType=" + moneyType + "&account=" + account + "&ts=" + new Date(), false);
19             xmlhttp.onreadystatechange = function () {
20                 if (xmlhttp.readyState == 4) {
21                     alert(xmlhttp.responseText);
22                     if (xmlhttp.status == 200) {
23                         alert(xmlhttp.responseText);
24                         //$("#result").text = xmlhttp.responseText;
25                         $("#result").val(xmlhttp.responseText);
26                     }
27                 }
28             }
29             xmlhttp.send();
30         }
31 
32     </script>
33 </head>
34 <body>
35     <input id="myaccount" type="text" name="name" value="" />
36     <select id="selectedID">
37         <option value="1" selected="selected">dollar</option>
38         <option value="2">Japan</option>
39         <option value="3">Hongkong</option>
40     </select>
41     <input type="button" name="name" value="check" onclick="btnOnclick()" />
42     <input type="text" name="name" value=" " id="result"/>
43 </body>
44 </html>
ashx代碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace AJAX
 7 {
 8     /// <summary>
 9     /// _02匯率問題 的摘要說明
10     /// </summary>
11     public class _02匯率問題 : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             //context.Response.Write("Hello World");
18             //get two accounts from html
19             string moneyType = context.Request["moneyType"];
20             int account = Convert.ToInt32(context.Request["account"]);
21 
22             if (moneyType == "1")//dollar
23             {
24                 context.Response.Write(account/7);
25             }
26             else if(moneyType=="2")//Japan
27             {
28                 context.Response.Write(account*10);
29             }
30             else//Hongkong
31             {
32                 context.Response.Write(account*10/9);
33             }
34         }
35 
36         public bool IsReusable
37         {
38             get
39             {
40                 return false;
41             }
42         }
43     }
44 }

!!!遇到問題總結:
        xmlhttp.open("POST", "02" + encodeURI('匯率問題') + ".ashx?moneyType=" + moneyType + "&account=" + account + "&ts=" + new Date(), false);這句代碼中,用到中文字符都要用encodeURl來轉化字符類型,不僅僅是參數,頁面名稱亦如是。

       $("#result").val(xmlhttp.responseText);將xmlhttp獲取得到的文本數據傳給val()。

3、JQuery AJAX

       (1、newActiveXObject("Microsoft.XMLHTTP")是IE中創建XMLHttpRequest對象的方法。非IE瀏覽器中創建方法是newXmlHttpRequest()。為了兼容不同的瀏覽 器需要編寫很多代碼,下面的兼容瀏覽器也不是很完整的:
  
兼容不同瀏覽器的XMLhttpresquest對象
 1 function CreateXmlHttp()
 2 
 3         {
 4 
 5             varxmlhttp;
 6 
 7             //非IE瀏覽器創建XmlHttpRequest對象
 8 
 9             if (window.XmlHttpRequest)
10 
11             {
12 
13                 xmlhttp =new XmlHttpRequest();
14 
15             }
16 
17             //IE瀏覽器創建XmlHttpRequest對象
18 
19             if (window.ActiveXObject)
20 
21             {
22 
23                 try
24 
25                 {
26 
27                     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
28 
29                 }
30 
31                 catch (e)
32 
33                 {
34 
35                     try
36 
37                     {
38 
39                         xmlhttp = new ActiveXObject("msxml2.XMLHTTP");
40 
41                     }
42 
43                     catch (ex) {alert("AJAX創建失敗!");}
44 
45                 }
46 
47             }
48 
49             return xmlhttp;
50 
51         }

       (2、采用JQueryAJAX方式可以高效化解瀏覽器問題:JQuery中提供了簡化ajax使用的方法。$.ajax()函數是JQuery中提供的ajax訪問函數,

     $.post()是對$.ajax()的post方式提交ajax查詢的封裝,$.get()是對$.ajax()的get方式提交ajax查詢的封裝。推薦用post方式,因為post方式沒有緩存的問題
案例1:對前面的匯率問題進行修改簡化

JQuery改進匯率兌換問題
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>02 huilv question</title>
 5     <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
 6     <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
 7     <script type="text/javascript">
 8         function btnOnclick_01() {//just test ,nothing
 9             $.post("01AJAX.ashx", function (data, textSize) {
10                 if (textSize == "success") {
11                     alert(data);
12                 } else {
13                     alert("AJAX create a error!!!");
14                 }
15             });
16 
17         }
18         function btnOnclick_02() {// huilv question
19             var account = $("#myaccount").val();
20             var moneyType = $("#selectedID").val();
21             $.post("03JQuery" + encodeURI('匯率問題') + ".ashx", { "account": account, "moneyType": moneyType }, function (data, textSize) {
22                 if (textSize == "success") {
23                     alert(data);
24                 } else {
25                     alert("AJAX create a error!!!");
26                 }
27             });
28 
29         }
30     </script>
31 </head>
32 <body>
33     <input id="myaccount" type="text" name="name" value="" />
34     <select id="selectedID">
35         <option value="1" selected="selected">dollar</option>
36         <option value="2">Japan</option>
37         <option value="3">Hongkong</option>
38     </select>
39     <input type="button" name="name" value="Just_test" onclick="btnOnclick_01()" />
40     <input type="button" name="name" value="check" onclick="btnOnclick_02()" />
41     <input type="text" name="name" value=" " id="result"/>
42 </body>
43 </html>

 4、練習

 練習1:JQuery實現Ajax 根據商品名稱自動顯示價格
html代碼
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>search the price problem</title>
 5     <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
 6     <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
 7     <script type="text/javascript">
 8         $(function () {
 9             $("#myinput").blur(function () {
10                 var name = $("#myinput").val();
11                 $.post("GetPrice.ashx", { "name": name }, function (data, istatus) {
12                     if (istatus == "success") {
13                         var myArray = data.split("|");
14                         if (myArray[0] == "ok") {
15                             $("#result").val(myArray[1]);
16                         }
17                         else if (myArray[0] == "none") {
18                             alert("No Sale!");
19                         } else {
20                             alert("error data!");
21                         }
22                     } else {
23                         alert("AJAX error!s");
24                     }
25                 });
26             });
27         });
28     </script>
29 </head>
30 <body>
31     <input id="myinput" type="text" name="name" value="" />
32     <input type="text" name="name" value=" " id="result"/>
33 </body>
34 </html>
ashx代碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using AJAX.DAL.DataSet1TableAdapters;
 6 
 7 namespace AJAX
 8 {
 9     /// <summary>
10     /// _02匯率問題 的摘要說明
11     /// </summary>
12     public class GetPrice : IHttpHandler
13     {
14 
15         public void ProcessRequest(HttpContext context)
16         {
17             context.Response.ContentType = "text/plain";
18             //context.Response.Write("Hello World");
19             string name = context.Request["name"];
20             var data = new buyTableAdapter().GetDataByName(name);
21             if(data.Count<=0)
22             {
23                 context.Response.Write("none|0");
24             }
25             else
26             {
27                 context.Response.Write("ok|"+data.Single().Price);
28             }
29             //context.Response.Write("happy");
30         }
31 
32         public bool IsReusable
33         {
34             get
35             {
36                 return false;
37             }
38         }
39     }
40 }

!!!遇到問題總結:

        發現錯誤,調試了半天,但是根本無法進入到應該處理的代碼段進行調試。后來經過一番查找,得出原因!!!

        我是直接從之前的其他頁面拷貝整個ashx 文件然后修改成到現在的文件,VS2010 沒有自動幫我修改ashx文件所指向的類,必須手工進行修改。

          解決方法:右鍵點擊該 ashx 文件,選擇“查看標記”,在打開的編輯界面中,修改 Class 項,改為新項目所指向命名空間下的類名。

 練習2:無刷新評論帖子
    方法1:評論采用AJAX,但采用Repeater動態顯示列表
html代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewByRepeater.aspx.cs" Inherits="AJAX.ReviewByRepeater1" %>

<!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 runat="server">
    <title></title>
    <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#Button1").click(function () {
                var msg = $("#TextArea1").val();
                $.post("ReviewByRepeater.ashx", { "msg": msg }, function (data, istaus) {
                    if (istaus != "success") {
                        alert("failed!");
                        return;
                    }
                    if (data == "ok") {
                        var newComment = $("<li>PostDate:" + new Date() + "IP:me,內容:" + msg + "</li>");
                        $("#ulCommentId").append(newComment);
                        alert("success!");
                    }
                    else {
                        alert("error!");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
            DeleteMethod="Delete" InsertMethod="Insert" 
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" 
            TypeName="AJAX.DAL.DataSet1TableAdapters.T_PostsTableAdapter" 
            UpdateMethod="Update">
            <DeleteParameters>
                <asp:Parameter Name="Original_ID" Type="Int64" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="IPAdrr" Type="String" />
                <asp:Parameter Name="Msg" Type="String" />
                <asp:Parameter Name="PostDate" Type="DateTime" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="IPAdrr" Type="String" />
                <asp:Parameter Name="Msg" Type="String" />
                <asp:Parameter Name="PostDate" Type="DateTime" />
                <asp:Parameter Name="Original_ID" Type="Int64" />
            </UpdateParameters>
        </asp:ObjectDataSource>
        <ul id="ulCommentId">
        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
            <ItemTemplate><li>Posdate:<%#Eval("PostDate") %>,IP:<%#Eval("IPAdrr") %>,內容:<%#Eval("Msg") %></li></ItemTemplate>
        </asp:Repeater>
        </ul>
        <br />
        <textarea id="TextArea1" cols="20" rows="2"></textarea>
        <input id="Button1" type="button" value="button" />
    </div>
    </form>
</body>
</html>
ashx代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DAL.DataSet1TableAdapters;

namespace AJAX
{
    /// <summary>
    /// ReviewByRepeater 的摘要說明
    /// </summary>
    public class ReviewByRepeater : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string msg = context.Request["msg"];
            new T_PostsTableAdapter().Insert(context.Request.UserHostAddress,msg,DateTime.Now);
            context.Response.Write("ok");
        }

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

   方法2:評論和列表均采用AJAX,完全靜態操作

html代碼
<!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 src="js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.post("ReviewByAjax.ashx", function (data, istaus) {
                alert(data);
                //alert(istaus);
                if (istaus != "success") {
                    $("#bodyComment").append($("<li>加載失敗</li>"));
                }
                var mydata = data.split("$");
                for (var i = 0; i < mydata.length; i++) {
                    var rowdata = mydata[i].split("|");
                    var comment = $("<li> IP:" + rowdata[0] + ",PostDate:" + rowdata[1]
                        + ",內容:" + rowdata[2]+"</li>");
                    $("#bodyComment").append(comment);
                }
            });
        });
    </script>
</head>
<body id="bodyComment">

</body>
</html>
ashx代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DAL.DataSet1TableAdapters;
using System.Text;

namespace AJAX
{
    /// <summary>
    /// ReviewByAjax1 的摘要說明
    /// </summary>
    public class ReviewByAjax : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            var comments = new T_PostsTableAdapter().GetData();
            StringBuilder sb = new StringBuilder();
            foreach (var comment in comments)
            {
                sb.Append(comment.IPAdrr).Append("|").Append(comment.PostDate)
                    .Append("|").Append(comment.Msg).Append("$");
            } 
            context.Response.Write(sb.ToString().Trim('$'));
        }

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

 總結:如果想要控制用戶的評論,例如禁止用戶輸入粗話等不文明用語,可以在ashx文件中添加  if(Msg.Contains("粗話")){return;}

 5、Json
 
         (1、ajax傳遞復雜數據如果自己進行格式定義的話會經歷組裝、解析的過程。因此ajax中有一個事實上的數據傳輸標准json,json將復雜對像序列化為一個字符串,在瀏覽端再將字符串反序列化為javascript可以讀取的對像,看一下json的格式, json被幾乎所有語言支持

         (2、c#中將.net對像序列化為json字符串的方法: javascriptserializer().serialize(p),javascriptSerializer在System.web.extensions.dll中,是net3.x中新增的類,如果在.net2.0則需要用第三方的組件。

          (3、Jquery ajax得到的data是Json格式數據,用$.parseJSON(data)方法將json格式數據解析為javaScript對像。

 練習1:用Json實現類中數據的傳遞
html代碼
<!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 src="js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.post("JsonText01.ashx", function (data, istaus) {
                var post = $.parseJSON(data);
                
                /*例子測試 1 */
                //alert(post.PostDate);
                /*例子測試 2 */
                //alert(post[0]);
                /*例子測試 3 */
                alert(post[1].PostDate);
            });
        });
    </script>
</head>
<body id="bodyComment">

</body>
</html>
ashx代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace AJAX
{
    /// <summary>
    /// JsonText01 的摘要說明
    /// </summary>
    public class JsonText01 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            JavaScriptSerializer jss=new JavaScriptSerializer();
            
            /*測試用例1
            string myJson = jss.Serialize(new Post() { PostDate = "2012-09-10",Msg="send new Mag!" });
            context.Response.Write(myJson);*/

            /*測試用例2
            string myJson = jss.Serialize(new string[] {"2012-09-10", "send new Mag!" });
            context.Response.Write(myJson);*/

            /*測試用例3*/
            Post[] posts = new Post[]
                               {
                                   new Post() {PostDate = "2012-09-10", Msg = "send old Mag!"},
                                   new Post() {PostDate = "2013-01-12", Msg = "send new Mag!"}
                               };
            string myJson = jss.Serialize(posts);
            context.Response.Write(myJson);
        }
        //q1:
        //JavaScriptSerializer要引用using System.Web.Script.Serialization;

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    public class Post
    {
        public string PostDate { set; get; }
        public string Msg { get; set; }
    }
}

總結:JavaScriptSerializer要引用using System.Web.Script.Serialization;但是using System.Web.Script.Serialization;引用的前提是引用System.web.extensions.dll

 練習2:用Json實現無刷新評論列表分頁

ashx代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using AJAX.DAL.DataSet1TableAdapters;
//高效分頁
namespace AJAX
{
    /// <summary>
    /// JsonText02 的摘要說明
    /// </summary>
    public class JsonText02 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];

            if (action == "getpagecount")  //如果請求的參數是getpagecount(獲取頁數)
            {
                var adapter = new T_PostsTableAdapter();
                int count = adapter.ScalarQuery().Value;  //獲取數據總條數
                int pageCount = count / 10;   //每頁只顯示10條

                if (count % 10 != 0)    //如果數據不夠10條,則只顯示第一頁
                {
                    pageCount++;
                }
                context.Response.Write(pageCount);   //返回頁數
            }
            else if (action == "getpagedata")   //如果請求的的參數是getpagedata(獲取評論內容)
            {
                string pagenum = context.Request["pagenum"];   //獲取客戶端點擊的是哪一頁
                int iPageNum = Convert.ToInt32(pagenum);
                var adapter = new T_PostsTableAdapter();
                // (iPageNum-1)*10+1  第一條數據,(iPageNum)*10 最后一條數據;
                var data = adapter.GetPageData((iPageNum - 1) * 10 + 1, (iPageNum) * 10);

                List<Comment> list = new List<Comment>();   //由於數據過於復雜所引發異常,定義一個Comment的類,內有postDate,comment兩個屬性;
                foreach (var row in data)   //遍歷data
                {
                    list.Add(new Comment()
                    {
                        PostDate = row.PostDate.ToShortDateString(),
                        Msg = row.Msg,
                        IPAdrr = row.IPAdrr
                    });
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                context.Response.Write(jss.Serialize(list));  //返回序列化的數據;
            }
        }

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

    public class Comment
    {
        public string PostDate { get; set; }
        public string Msg { get; set; }
        public string IPAdrr { get; set; }
    }
}
html代碼
<!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 src="js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <style type="text/css">
        ul
        {
            list-style: none;
            margin: 0px;
            padding: 0px;
        }
        li
        {
            border-bottom: 1px dashed #000;
            padding: 5px;
            font-family: "微軟雅黑";
            font-size: 12px;
        }
        .column
        {
            width: 80%;
            margin: 100px auto;
            padding: 10px;
            border: 1px solid #000;
        }
        p
        {
            background: #CCC;
            padding: 10px;
        }
        .divstyle
        {
            min-height: 50px;
            padding: 10px;
        }
        .trPage
        {
        }
    </style>
    <script type="text/javascript" language="javascript">
        $(function () {
            //請求默認顯示第一頁數據
            $.post("JsonText02.ashx", { "action": "getpagedata", "pagenum": "1" }, function (data, status) {
                alert(1);
                if (status == "success") {
                    var comments = $.parseJSON(data);
                    $("#ulComments li").remove();   //首先清空上一次的數據;
                    for (var i = 0; i < comments.length; i++) {
                        var comment = comments[i];
                        var li = $("<li><p>回復日期:" + comment.PostDate + "&nbsp;&nbsp;&nbsp;&nbsp;回復IP地址:" + comment.IPAdrr + "</p><div class='divstyle'>" + comment.Msg + "</div></li>");

                        $("#ulComments").append(li);
                    }
                }
            });
            $.post("JsonText02.ashx", { "action": "getpagecount" }, function (data, status) {
                for (var i = 1; i <= data; i++) {
                    var td = $("<td><a href=''>" + i + "</a></td>");
                    $(".trPage").append(td);
                }

                //給鏈接添加click事件
                $(".trPage td").click(function (e) {
                    e.preventDefault();

                    $.post("JsonText02.ashx", { "action": "getpagedata", "pagenum": $(this).text() }, function (data, status) {
                        var comments = $.parseJSON(data);  //使用JSON序列化數據;
                        $("#ulComments li").remove();   //首先清空上一次的數據;

                        for (var i = 0; i < comments.length; i++) {   //遍歷響應的數據data
                            var comment = comments[i];   //取到每條評論

                            //最后向ul中加載li(數據的內容)
                            var li = $("<li><p>回復日期:" + comment.PostDate + "&nbsp;&nbsp;&nbsp;&nbsp;回復IP地址:" + comment.IPAdrr + "</p><div class='divstyle'>" + comment.Msg + "</div></li>");
                            $("#ulComments").append(li);
                        }
                    });
                });
            });
        });
    </script>
</head>
<body>
    <div class="column">
        <table>
            <tr class="trPage">
            </tr>
        </table>
        <ul id="ulComments">
        </ul>
        <table>
            <tr class="trPage">
            </tr>
        </table>
    </div>
</body>
</html>
分頁的SQl語句
select * from
(
  SELECT ID, PostDate, Msg,IPAdrr,Row_Number() over(order by PostDate desc) rownum 
FROM dbo.T_Posts
)t 
where t.rownum>=@startRowIndex and t.rownum<=@endRowIndex

 練習3:用Json實現無刷新刪除評論

ashx代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DAL.DataSet1TableAdapters;

namespace AJAX
{
    /// <summary>
    /// JsonDelete03 的摘要說明
    /// </summary>
    public class JsonDelete03 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string id = context.Request["ID"];
            new T_PostsTableAdapter().DeleteById(Convert.ToInt32(id));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
aspx代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonDelete03.aspx.cs" Inherits="AJAX.JsonDelete031" %>

<!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 runat="server">
    <title></title>
    <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("input[isDelete=true]").click(function () {
                var myID = $(this).attr("id");
                $.post("JsonDelete03.ashx", { "ID": myID }, function (data, istaus) {
                    if (istaus == "success") {
                        alert("刪除成功!");
                        //在這里,$(this)指的不是控件本身而是這個位置
                        $("input[id=" + myID + "]").parent().parent().remove("tr");
                    }
                    else {
                        alert("刪除失敗,請聯系管理員");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete"
            InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
            TypeName="AJAX.DAL.DataSet1TableAdapters.T_PostsTableAdapter" UpdateMethod="Update">
            <DeleteParameters>
                <asp:Parameter Name="Original_ID" Type="Int64" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="IPAdrr" Type="String" />
                <asp:Parameter Name="Msg" Type="String" />
                <asp:Parameter Name="PostDate" Type="DateTime" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="IPAdrr" Type="String" />
                <asp:Parameter Name="Msg" Type="String" />
                <asp:Parameter Name="PostDate" Type="DateTime" />
                <asp:Parameter Name="Original_ID" Type="Int64" />
            </UpdateParameters>
        </asp:ObjectDataSource>
    </div>
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" DataSourceID="ObjectDataSource1"
        InsertItemPosition="LastItem">
        
        <edititemtemplate>
            <tr style="background-color: #999999;">
                <td>
                    <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="更新" />
                    <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="取消" />
                </td>
                <td>
                    <asp:Label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:TextBox ID="IPAdrrTextBox" runat="server" Text='<%# Bind("IPAdrr") %>' />
                </td>
                <td>
                    <asp:TextBox ID="MsgTextBox" runat="server" Text='<%# Bind("Msg") %>' />
                </td>
                <td>
                    <asp:TextBox ID="PostDateTextBox" runat="server" 
                        Text='<%# Bind("PostDate") %>' />
                </td>
            </tr>
        </edititemtemplate>
        <emptydatatemplate>
            <table runat="server" 
                style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
                <tr>
                    <td>
                        未返回數據。</td>
                </tr>
            </table>
        </emptydatatemplate>
        <insertitemtemplate>
            <tr style="">
                <td>
                    <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="插入" />
                    <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="清除" />
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:TextBox ID="IPAdrrTextBox" runat="server" Text='<%# Bind("IPAdrr") %>' />
                </td>
                <td>
                    <asp:TextBox ID="MsgTextBox" runat="server" Text='<%# Bind("Msg") %>' />
                </td>
                <td>
                    <asp:TextBox ID="PostDateTextBox" runat="server" 
                        Text='<%# Bind("PostDate") %>' />
                </td>
            </tr>
        </insertitemtemplate>
        <itemtemplate>
            <tr style="background-color: #E0FFFF;color: #333333;">
                <td>
                    <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="刪除" />
                    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="編輯" />
                <input type="button" isDelete="true" id='<%# Eval("ID") %>' value=" 無刷新刪除" />
                </td>
                <td>
                    <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:Label ID="IPAdrrLabel" runat="server" Text='<%# Eval("IPAdrr") %>' />
                </td>
                <td>
                    <asp:Label ID="MsgLabel" runat="server" Text='<%# Eval("Msg") %>' />
                </td>
                <td>
                    <asp:Label ID="PostDateLabel" runat="server" Text='<%# Eval("PostDate") %>' />
                </td>
            </tr>
        </itemtemplate>
        <layouttemplate>
            <table runat="server">
                <tr runat="server">
                    <td runat="server">
                        <table ID="itemPlaceholderContainer" runat="server" border="1" 
                            style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
                            <tr runat="server" style="background-color: #E0FFFF;color: #333333;">
                                <th runat="server">
                                </th>
                                <th runat="server">
                                    ID</th>
                                <th runat="server">
                                    IPAdrr</th>
                                <th runat="server">
                                    Msg</th>
                                <th runat="server">
                                    PostDate</th>
                            </tr>
                            <tr ID="itemPlaceholder" runat="server">
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr runat="server">
                    <td runat="server" 
                        style="text-align: center;background-color: #5D7B9D;font-family: Verdana, Arial, Helvetica, sans-serif;color: #FFFFFF">
                        <asp:DataPager ID="DataPager1" runat="server">
                            <Fields>
                                <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                                    ShowLastPageButton="True" />
                            </Fields>
                        </asp:DataPager>
                    </td>
                </tr>
            </table>
        </layouttemplate>
        <selecteditemtemplate>
            <tr style="background-color: #E2DED6;font-weight: bold;color: #333333;">
                <td>
                    <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="刪除" />
                    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="編輯" />
                </td>
                <td>
                    <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:Label ID="IPAdrrLabel" runat="server" Text='<%# Eval("IPAdrr") %>' />
                </td>
                <td>
                    <asp:Label ID="MsgLabel" runat="server" Text='<%# Eval("Msg") %>' />
                </td>
                <td>
                    <asp:Label ID="PostDateLabel" runat="server" Text='<%# Eval("PostDate") %>' />
                </td>
            </tr>
        </selecteditemtemplate>
    </asp:ListView>
    </form>
</body>
</html>

6、微軟中的AJAX應用

    (1、ASP.NET中內置的簡化AJAX開發的控件UPdatePanel

            ☆  放入ScriptManager,將要實現AJAX效果的控件放到UpdatePanel 中即可

            ☆ UpdatePanel遠離揭秘,用httpWatch看
                    原理:
                    缺點:通訊量傻瓜化過大,浪費流量,適合企業內部用。Timer就是實現定時AJAX效果,但是數據量也很大
 
            ☆ 只需要把無刷新更新的部分放到UPdatePanel中
    (2、用WCF簡化AJAX代碼量,讓javascript寫C#代碼
 
    (3、UpdateProgress顯示正在加載
 
7、WCF了解

1.開發步驟:
     ①添加一個Web項目 在Web項目中新建”新建項”→”Web”→”啟用了AJAX的WCF服務
     ②頁面上拖放ScriptManager控件 Services屬性中新增一項 Path屬性設置為服務路徑
     ③調用服務端方法時
              Service1.DoWork(OnDoWorkSuccess, OnDoWorkFailed);Service1為服務類名 DoWork為方法名 OnDoWorkSuccess為成功時回調函數 OnDoWorkFailed為失敗時回調函數 兩個函數都有一個參數result 成功時參數作為返回值 失敗時參數作為錯誤消息。服務器端還可以返回復雜對象 瀏覽器端可以直接從result讀取復雜對象的字段值

  8、全局文件

     (1、"web" 全局應用程序類(注意文件名不要改)

①全局文件是對Web應用生命周期的一個事件響應的地方
②將Web應用啟動時初始化的一些代碼寫到Application_Start中(如Log4Net等)
③Web應用關閉時Application_End調用
④Session啟動時Session_Start調用
⑤Session結束(用戶主動退出或者超時結束)時Session_End調用
⑥當一個用戶請求來的時候Application_BeginRequest調用
⑦當應用程序中出現未捕獲異常時Application_Error調用(通過HttpContext.Current.Server.GetLastError()獲得異常信息 然后用Log4Net記錄到日志中)

練習:禁止盜鏈和IP地址禁止

Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace AJAX
{
    public class Global : System.Web.HttpApplication
    {
        //程序啟動的時候執行的代碼
        protected void Application_Start(object sender, EventArgs e)
        {

        }
        //調用Session信息開始
        protected void Session_Start(object sender, EventArgs e)
        {
            //HttpContext.Current.Session.Abandon();//結束Session
        }
        //每次請求都會觸發
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //通過HttpContext.Current.Request.Url查看來源
            //用途1:可以在這里屏蔽IP地址
            if(HttpContext.Current.Request.UserHostAddress=="127.0.0.1")
            {
                HttpContext.Current.Response.Write("已屏蔽,請聯系管理員");
                HttpContext.Current.Response.End();
            }
            //用途2:防盜鏈
            if(HttpContext.Current.Request.Url.AbsolutePath.EndsWith("/JPG")&& HttpContext.Current.Request.UrlReferrer.Host!="localhost")
            {
                //localhost:如果是正式上線則是域名地址
                HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/DSCF0802.JPG"));
                HttpContext.Current.Response.End();
            }

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }
        //程序發生異常的時候,就會被捕獲,拋出異常(ASP.NET錯誤處理:錯誤頁和Application_Error)
        protected void Application_Error(object sender, EventArgs e)
        {
            /*如果在aspx頁面中 throw new exception("error");
                   HttpContext.Current.Server.GetLastError()獲得異常信息,
             *   然后用log4Net記錄到錯誤處理機制中
             */
        }
        //Session時間到后終止
        protected void Session_End(object sender, EventArgs e)
        {

        }
        //程序結束的時候執行的代碼(只執行一次)
        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

9、URL重寫

  1. SEO(Search Engine Optimization): 搜索引擎優化
  2. URL重寫(URLRewrite 偽靜態):搜索引擎優化也方便用戶看
  3. Site:cnblogs.com  能看百度收錄了多少網頁

    !!!實現:當打開View-1.aspx、View-2.aspx重寫,都是指向同一個頁面

 原理: 在Global.asax的Application_BeginRequest中讀取請求的URL並使用HttpContext.Current.Rewrite()進行重寫
  Regex reg = new Regex(“.+View-(\d+).aspx”);
  var m1 = reg.Match(HttpContext.Current.Request.Url.AbsolutePath);
  if(macth.Success)
  {
    string id = match.Groups[1].Value;
    HttpContext.Current.RewitePath(“View.aspx?id=” + id);
  }

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM