加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.NET运用AJAX 总结及其实例

发布时间:2020-12-16 01:55:56 所属栏目:百科 来源:网络整理
导读:1、 AJAX简介 (1、没有AJAX会怎么样?普通的ASP.Net每次执行服务端方法的时候都要刷新当前页面,比如实现显示服务器的时间。每次都要刷新页面的坏处: 页面刷新打断用户操作、速度慢、增加服务器的流量压力 。如果没有AJAX,在youku看视频的过程中如果点击

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发送请求,获得返回的数据并且显示到界面上。下面的代码非常重要,是精华来着,必背:
 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</ 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=+  Date(),false23             
24             xmlhttp.onreadystatechange  () {
25                  (xmlhttp.readyState == 4) {readyState == 4 表示服务器返回数据了
26                      (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     script40 41 body42     input ="text" id="txtTime" />
43     ="button"="btn" value onclick="btnClick()" 44 45 html>
 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     /// 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         }
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",false),如果这样单纯滴传两个静态参数的话,浏览器可能会保持一
种提取缓存的状态,所以最好传一个动态参数,随意一个参数。这是一个AJAX缓冲存在的问题。如果用POST的方式,就不会发生缓冲的问题。
案例1:无刷新异步操作-->汇率转换
>02 huilv questionsrc="js/jquery-1.4.2.js" type></ 6     ="js/jquery-1.4.2-vsdoc.js" 7      8          btnOnclick() {
 moneyType  $(#selectedID).val();
10              account #myaccountalert(account);
12             alert(moneyType);
13             =14             15 error from create xmlhttp!16                 17 18 02汇率问题.ashx?moneyType=&account=19 20                 ) {
21                     alert(xmlhttp.responseText);
22                     23                         alert(xmlhttp.responseText);
24                         $("#result").text = xmlhttp.responseText;
25                         $(#result).val(xmlhttp.responseText);
26 27             xmlhttp.send();
30 31 
32     33 34 35     id="myaccount" name="name"="" 36     select ="selectedID"37         option value="1" selected="selected">dollaroption38         ="2">Japan39         ="3">Hongkong40     select41     ="check"="btnOnclick()" =" "="result"43 >
 9     /// _02汇率问题 的摘要说明
11     public class _02汇率问题 : IHttpHandler
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"]);
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()。为了兼容不同的浏览 器需要编写很多代码,下面的兼容浏览器也不是很完整的:
 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)
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:对前面的汇率问题进行修改简化

 btnOnclick_01() {just test,nothing
 9             $.post(01AJAX.ashx (data,textSize) {
10                  (textSize success11                     alert(data);
                } 13                     alert(AJAX create a error!!!            });
18          btnOnclick_02() { huilv question
20             03JQuery.ashxaccount: account,245)">moneyType: moneyType },128); line-height:1.5!important">22                 30     31 32 33     34     35         36         38     ="Just_test"="btnOnclick_01()" ="btnOnclick_02()" 42 >

4、练习

练习1:JQuery实现Ajax 根据商品名称自动显示价格
>search the price problem 8         $(            $(#myinput).blur( name                 $.post(GetPrice.ashxname: name },istatus) {
12                      (istatus 13                          myArray  data.split(|14                          (myArray[0] ok                            $().val(myArray[1]);
16                         }
17                         else none                            alert(No Sale!                        } 20 error data!                    } AJAX error!s                });
        });
28     29 30 31     ="myinput" 
   
  
 5 using AJAX.DAL.DataSet1TableAdapters;
 7 namespace AJAX
 8 {
 9     /// 10     /// _02汇率问题 的摘要说明
11     /// 12     public class GetPrice : IHttpHandler
13     {
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         }
32         public bool IsReusable
33         {
34             get
35 36                 return false;
37 38 39     }
40 }

!!!遇到问题总结:

发现错误,调试了半天,但是根本无法进入到应该处理的代码段进行调试。后来经过一番查找,得出原因!!!

我是直接从之前的其他页面拷贝整个ashx 文件然后修改成到现在的文件,VS2010 没有自动帮我修改ashx文件所指向的类,必须手工进行修改。

解决方法:右键点击该 ashx 文件,选择“查看标记”,在打开的编辑界面中,修改 Class 项,改为新项目所指向命名空间下的类名。

练习2:无刷新评论帖子
方法1:评论采用AJAX,但采用Repeater动态显示列表
<%@ Page Language="C# AutoEventWireuptrue CodeBehindReviewByRepeater.aspx.cs InheritsAJAX.ReviewByRepeater1" %>

>

head runat="server">
    >
        $( () {
            $(#Button1).click( () {
                 msg #TextArea1).val();
                $.post(ReviewByRepeater.ashxmsg: msg },istaus) {
                     (istaus != ) {
                        alert(failed!);
                        ;
                    }
                     (data ) {
                         newComment <li>PostDate: Date() IP:me,内容:</li>);
                        $(#ulCommentId).append(newComment);
                        alert(success!);
                    }
                     {
                        alert(error!);
                    }
                });
            });
        });
    form ="form1" runatdiv>
        asp:ObjectDataSource ID="ObjectDataSource1"="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" />
            InsertParameters="IPAdrr"="String" />
                ="Msg"="PostDate"="DateTime" UpdateParametersasp:ObjectDataSourceul ="ulCommentId"asp:Repeater ="Repeater1" DataSourceID="ObjectDataSource1"ItemTemplate><li>Posdate:#Eval(PostDate) %>,IP:IPAdrrMsg%>asp:Repeaterulbr />
        textarea ="TextArea1" cols="20" rowstextarea="Button1"="button" />
    form 
   
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DAL.DataSet1TableAdapters;

namespace AJAX
{
    /// >
    /// ReviewByRepeater 的摘要说明
    /// >
    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,完全静态操作

 () {
            $.post(ReviewByAjax.ashxalert(istaus);
                ) {
                    $(#bodyComment).append($(<li>加载失败</li>));
                }
                 mydata $);
                for ( i = ; i < mydata.length; i++) {
                     rowdata  mydata[i].split();
                     comment <li> IP: rowdata[]
                        2]);
                    $().append(comment);
                }
            });
        });
    body ="bodyComment" 
   
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DAL.DataSet1TableAdapters;
using System.Text;

namespace AJAX
{
    /// >
    /// ReviewByAjax1 的摘要说明
    /// >
    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实现类中数据的传递
JsonText01.ashx post  $.parseJSON(data);
                
                /*例子测试 1 */
                alert(post.PostDate);
                例子测试 2 alert(post[0]);
                例子测试 3 */
                alert(post[].PostDate);
            });
        });
     
   
  
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
    {

        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!"},0); line-height:1.5!important">2013-01-12send new Mag!"}
                               };
            string myJson = jss.Serialize(posts);
            context.Response.Write(myJson);
        }
        q1:
        JavaScriptSerializer要引用using System.Web.Script.Serialization;

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

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

练习2:用Json实现无刷新评论列表分页

using System.Web.Script.Serialization;
using AJAX.DAL.DataSet1TableAdapters;
高效分页
 JsonText02 的摘要说明
    class JsonText02 : IHttpHandler
    {

        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 getpagedata")   如果请求的的参数是getpagedata(获取评论内容)
            {
                string pagenum = context.Request[pagenum"];   获取客户端点击的是哪一页
                int iPageNum = Convert.ToInt32(pagenum);
                 (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));  返回序列化的数据;
            }
        }

        false;
            }
        }
    }

    class Comment
    {
        set; }
        string IPAdrr { set; }
    }
}
style ="text/css">
        ul
        {
            list-style: none;
            margin 0px
            padding;
        }
        li
        
            border-bottom 1px dashed #000 5px
            font-family "微软雅黑"
            font-size 12px
        .column
        
            width 80% 100px auto 10px
            border 1px solid #000
        p
        
            background #CCC
        .divstyle
        
            min-height 50px
        .trPage
        {
        }
    style="text/javascript" language="javascript" () {
            请求默认显示第一页数据
JsonText02.ashxaction: getpagedatapagenum },status) {
                alert( (status  comments  $.parseJSON(data);
                    $(#ulComments li).remove();   首先清空上一次的数据;
                     comments.length; i comments[i];
                         li <li><p>回复日期: comment.PostDate &nbsp;&nbsp;&nbsp;&nbsp;回复IP地址: comment.IPAdrr </p><div class='divstyle'> comment.Msg </div></li>);

                        $(#ulComments).append(li);
                    }
                }
            });
            $.post(getpagecount<= data; i td <td><a href=''></a></td>.trPage).append(td);
                }

                给链接添加click事件
                $(.trPage td (e) {
                    e.preventDefault();

                    $.post(: $(this).text() },status) {
                         $.parseJSON(data);  使用JSON序列化数据;
首先清空上一次的数据;

                        ) {   遍历响应的数据data
                             comments[i];   取到每条评论

                            最后向ul中加载li(数据的内容)
                            );
                            $().append(li);
                        }
                    });
                });
            });
        });
    div class="column"tabletr ="trPage"tr="ulComments" 
   
  
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实现无刷新删除评论

using AJAX.DAL.DataSet1TableAdapters;

 JsonDelete03 的摘要说明
    class JsonDelete03 : IHttpHandler
    {

        context.Response.Write("Hello World");
            string id = context.Request[ID"];
            new T_PostsTableAdapter().DeleteById(Convert.ToInt32(id));
        }

        false;
            }
        }
    }
}
JsonDelete03.aspx.csAJAX.JsonDelete031input[isDelete=true] myID  $().attr(id);
                $.post(JsonDelete03.ashxID: myID },245)">删除成功!在这里,$(this)指的不是控件本身而是这个位置
input[id=).parent().parent().remove(tr删除失败,请联系管理员 DeleteMethod
            InsertMethod OldValuesParameterFormatString
            TypeName UpdateMethodasp:ListView ="ListView1" DataKeyNames="ID"
        InsertItemPosition="LastItem">
        
        edititemtemplate="background-color: #999999;"td>
                    asp:Button ="UpdateButton" CommandName="Update" Text="更新" />
                    ="CancelButton"="Cancel"="取消" asp:Label ="IDLabel1"='<%# Eval("ID") %>' />
                asp:TextBox ="IPAdrrTextBox"Bind("IPAdrr") %="MsgTextBox"Bind("Msg") %="PostDateTextBox" 
                        TextBind("PostDate") %emptydatatemplatetable  
                style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
                        未返回数据。insertitemtemplate=""="InsertButton"="插入" ="清除" >
                    &nbsp;itemtemplate="background-color: #E0FFFF;color: #333333;"="DeleteButton"="删除" ="EditButton"="Edit"="编辑"  isDelete="true">' value=" 无刷新删除" />
                ="IDLabel"="IPAdrrLabel"Eval("IPAdrr") %="MsgLabel"Eval("Msg") %="PostDateLabel"Eval("PostDate") %layouttemplatetd >
                        ="itemPlaceholderContainer" border 
                            style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana,sans-serif;">
                             style>
                                th th>
                                    ID>
                                    IPAdrr>
                                    Msg>
                                    PostDate="itemPlaceholder" 
                        style="text-align: center;background-color: #5D7B9D;font-family: Verdana,sans-serif;color: #FFFFFF"asp:DataPager ="DataPager1"Fieldsasp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                                    ShowLastPageButton="True" />
                            asp:DataPagerselecteditemtemplate="background-color: #E2DED6;font-weight: bold;color: #333333;"asp:ListView>

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地址禁止

using System.Web.Security;
using System.Web.SessionState;

namespace AJAX
{
    class Global : System.Web.HttpApplication
    {
        程序启动的时候执行的代码
        protected void Application_Start(object sender,EventArgs e)
        {

        }
        调用Session信息开始
        void Session_Start(HttpContext.Current.Session.Abandon();结束Session
        }
        每次请求都会触发
        void Application_BeginRequest(通过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();
            }

        }

        void Application_AuthenticateRequest(程序发生异常的时候,就会被捕获,抛出异常(ASP.NET错误处理:错误页和Application_Error)
        void Application_Error(如果在aspx页面中 throw new exception("error");
                   HttpContext.Current.Server.GetLastError()获得异常信息,
             *   然后用log4Net记录到错误处理机制中
             */
        }
        Session时间到后终止
        void Session_End(程序结束的时候执行的代码(只执行一次)
        void Application_End( 
    
  

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);   }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读