zoukankan      html  css  js  c++  java
  • jquery+ajax+ashx

    转自:http://www.cnblogs.com/myaspnet/archive/2010/11/12/1876101.html

    1、使用一般的webform,在页面用jQuery ajax调用,再从取得的html数据中取得<body>内的内容,写入DOM

    优点:不用改变现有的asp.net开发模式,可以使用现成的页面;ajax取得的内容是html文本,直接写入DOM即可 
    缺点:内容浪费,<body>之外的内容都不是必要的,而且如果使用了MasterPage那就。。。

    2、使用一般的webform,但是用Response.Write()控制输出html,在页面用jQuery ajax调用,将获取的内容写入DOM

    优点:内容干净,不浪费;ajax取得的内容是html文本,可以直接写入DOM 
    缺点:需要在服务器端以字符串形式构造html文本,编程不方便,不容易调试和维护

    3、使用一般的webform,用Response.Write()控制输出json数据,在页面用jQuery ajax调用,将json数据在客户端加工成html后写入DOM

    优点:仅仅交换json数据,极干净,符合高效的web设计理念 
    缺点:需要在客户端加工json数据,并且对DOM造成入侵

    4、使用asmx,封装成web service,用jQuery ajax调用asmx的内容,将json或者xml数据在客户端加工成html后写入DOM 
    优点:仅仅交换json或/xml数据,非常干净;web service易于跨平台 
    缺点:需要在客户端加工json数据,并且对DOM造成入侵

    5、使用自定义控件ascx,然后使用专门的webform页面做wrapper(包装)在页面用jQuery ajax调用wrapper webform,将html数据写入DOM

    优点:webform仅仅用作wrapper,根据不同的请求参数可以在wrapper中动态使用自定义控件;自定义控件输出的是html文本,可以直接写入DOM;编程方便,有VS2008代码感知支持,易于调试和维护 
    缺点:跟传统的webform编程理念不一样,弱化了webform的作用

    以上就是讨论的几种可行的方案——不管是asp.net webform方式还是asp.net MVC方式,都是可行的。
    昨天晚上又发现一种方案:使用ashx+jQuery .ashx是一个专门的用于处理HttpHandler的文件类型,用来处理自定义Http请求,可以在web.config定义运行时针对ashx的Http请求处理方式。

    <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" validate="false" />

    这样我们就可以用SimpleHandlerFactory来处理ashx的http请求了。在ashx的类中实现IRequiresSessionState接口,using下System.Web.SessionState就可以使用Session了,很方便

    using System.Web.SessionState;     
    public class checkCookie : IHttpHandler,IRequiresSessionState 
    {   
         ...  // todo somthing 
    }

    实例:使用ashx+jQuery实现Email存在的验证 
    .ashx文件 
    <%@ WebHandler Language="C#" class="CheckUser" %>

    using System;using System.Web;   
    public class CheckUser : IHttpHandler 

         public void ProcessRequest (HttpContext context) 
        {      
              context.Response.ContentType = "text/plain"; 
              context.Response.Write(UserRule.GetInstance().IsUserExist(context.Request["Email"])); 
        } 
         public bool IsReusable 
        { 
             get { 
                return false; 
            } 
        } 
    }

    html: 
    <input type="text" id="email" /> 
    <input type="button" value="test" onclick="check_email()" />

    js: 
    function check_email() 

        var email = $("#email").attr("value"); 
         $.get("../ajax/checkuser.ashx", 
        { Email: email }, 
         function(data) 
         { 
            window.alert(data); 
          }); 
    }

    simple的,显然效率会比较高。不过simple的就只能够做点simple的事情。如果要输出html,还是不太方便。如果要输出html的话,我还是比较倾向于用ascx处理内容,webform做包装所以 ashx+jQuery应该算是是一个asp.net里轻量级的解决方案

    asp.net中jQuery $post用法

    函数原型:$.post(url,params, callback)  

    url是提交的地址,eg: "sample.ashx"

    params是参数,eg: { name:"xxx" , id:"001" }

    callback是回调函数,eg: function(msg){ alert(msg); }

    注意1:在sample.ashx那段,使用context.Request["id"]和context.Request["name"]来分别获得值"001"和值"xxx",而不是使用context.Request.QueryString["id"]

    注意2:这里的callback里的函数是在服务器返回值后被触发,所以不需要另行判断xmlHttp.readyState==4 &&xmlHttp.status==200

    接下来,我们来用一段代码比较一下$.post方式和原始的xmlHttp方式

    为了更好的对应,我让2个方式实现一样的功能,传的值和回调函数的名字一样

    /* xmlHttp方式 */

       var xmlHttp;    //定义对象xmlHttp
        functioncreateXMLHttpRequest()        //创建xmlHttpRequest的函数
        {
    if(window.ActiveXObject)
    {
    xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
    }
    else if(window.XMLHttpRequest)
    {
    xmlHttp = newXMLHttpRequest();              
    }
    }

        function btn_onclick()      //假设一个button点了以后触发这个ajax
    {
    createXMLHttpRequest();
    var url="sample.ashx?id=1&name=a";    //这里假设传给sample.ashx,传2个值,id=1和name=a
           xmlHttp.open( "POST" ,url,true);
    xmlHttp.onreadystatechange=Response; //回调函数是Response()
           xmlHttp.send(null);   
    }

       functionResponse()
    {
    if( xmlHttp.readyState==4 && xmlHttp.status==200 )
    {
    alert( xmlHttp.responseText );       //弹出一个框显示服务器返回的内容
            }
    }

    /* $.post方式 */

    function btn_onclick()      //同样还是这个事件和函数,还是点了以后触发
      {      

    /*

    同样还是sample.ashx,同样是id=1&name=a
    这里的function(msg)是回调的函数,你可以把执行的内容直接写在{}里,msg表示服务器返回的数据。
    为了和上面的方式更好的对应起来,我这里依然让他调用Response,但是需要增加参数msg

    */ 
    $.post("sample.ashx",{ id:"1",name:"a" }, function(msg){ Response(msg); });   

        }

       function Response(msg)
    {
    alert( msg );       //弹出一个框显示服务器返回的内容
        }

    jquery+ajax+asp.net实现Ajax操作

    转载 2010-05-17 01:46:41阅读143 评论0 字号:大中小

    文章简介:关于jquery+ajax+asp.net实现Ajax操作的简介

    jquery,ajax,asp.net

    是jquery+ajax+ashx的   现在这个是Handler.ashx:

    ========================================================================

    <%@ WebHandlerLanguage="C#" class="Handler" %>

    using System;

    using System.Web;

    ...jquery+ajax+asp.net实现Ajax操作

    是jquery+ajax+ashx的   现在这个是Handler.ashx:

    ========================================================================

    <%@ WebHandlerLanguage="C#" class="Handler" %>

    using System;

    using System.Web;

    public class Handler :IHttpHandler {

        publicvoid ProcessRequest (HttpContext context) {

            charmethod = Convert.ToChar(context.Request.Params["m"]);

            context.Response.ContentType= "text/plain";

            switch(method)

            {

                case'a':

                    context.Response.Write("HelloWorld<br/>This is a sample");

                    return;

                case'b':

                    context.Response.Write("HelloWorld<br/>This is b sample");

                    return;                

            }

            context.Response.Flush();  

        }

    }

    ================================================================

    jquery调用代码:

    =================================================================

    $(document).ready(function(){

                $("#test2").click(function(){

                    $.ajax({

                        type: "post",

                        url: "Handler.ashx",

                        data: {m:'a'},

                        success: function(result){

                            $("#testText").append(result+ "<br/>");

                        }

                    });

                });

            });

            $(document).ready(function(){

                $("#test3").click(function(){

                    $.ajax({

                        type: "post",

    文章简介:关于jquery+ajax+asp.net实现Ajax操作的简介

    jquery,ajax,asp.net

    是jquery+ajax+ashx的   现在这个是Handler.ashx:

    ========================================================================

    <%@ WebHandlerLanguage="C#" class="Handler" %>

    using System;

    using System.Web;

    ...jquery+ajax+asp.net实现Ajax操作

    是jquery+ajax+ashx的   现在这个是Handler.ashx:

    ========================================================================

    <%@ WebHandlerLanguage="C#" class="Handler" %>

    using System;

    using System.Web;

    public class Handler :IHttpHandler {

        publicvoid ProcessRequest (HttpContext context) {

            charmethod = Convert.ToChar(context.Request.Params["m"]);

            context.Response.ContentType= "text/plain";

            switch(method)

            {

                case'a':

                    context.Response.Write("HelloWorld<br/>This is a sample");

                    return;

                case'b':

                    context.Response.Write("HelloWorld<br/>This is b sample");

                    return;                

            }

            context.Response.Flush();  

        }

    }

    ================================================================

    jquery调用代码:

    =================================================================

    $(document).ready(function(){

                $("#test2").click(function(){

                    $.ajax({

                        type: "post",

                        url: "Handler.ashx",

                        data: {m:'a'},

                        success: function(result){

                            $("#testText").append(result+ "<br/>");

                        }

                    });

                });

            });

            $(document).ready(function(){

                $("#test3").click(function(){

                    $.ajax({

                        type: "post",

                        url: "Handler.ashx",

                        data: {m:'b'},

                        success: function(result){

                            $("#testText").append(result+ "<br/>");

                        }

                    });

                });

            });

                        url: "Handler.ashx",

                        data: {m:'b'},

                        success: function(result){

                            $("#testText").append(result+ "<br/>");

                        }

                    });

                });

            });

    己虽然以前也用ajax但总感觉那里觉得不对,以前ajax都是请求aspx页面,那页面多的数不清,自己也觉得很乱。

    自己最近在工作中,也觉得同事用的jquery+ashx用起来相当的简洁方便。帮在这里做了一个小的demo来

    <%@ Page Language="C#"AutoEventWireup="true" CodeFile="AjaxGet.aspx.cs"Inherits="AjaxGet" %>

    <!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>

        <scripttype="text/javascript" src="misc/js/jquery-1.2.6.js"></script>

    </head>

    <body>

    <script type="text/javascript"language="javascript">

     function GetCategoryData(type)

     {

     alert("test start");

      $.ajax({

      type:'GET',

      url:'AjaxService/Handler.ashx',

      dataType: 'text',

      data:'type='+type,

      success:function(msg)

      {

      alert(msg);

      $("#category").html(msg);

      },

      error: function(data){

      alert(data);

      }

      })

     }

    </script>

        <form id="form1"runat="server">

        <div>

        <input type="radio"value="1" name="wangtao" onclick='GetCategoryData(this.value)' />

        <input type="radio"value="2" name="wangtao" onclick='GetCategoryData(this.value)'/>

        <select id="category" >

        </select>

        </div>

        </form>

    </body>

    </html>

    前台页后很简单了,就是两个radio和一个select。要把选中的radio的值放在select中去。

    后台ashx代码

    <%@ WebHandler Language="C#"Class="Handler" %>

    using System;

    using System.Web;

    using System.Text;

    public class Handler : IHttpHandler {

        public void ProcessRequest (HttpContextcontext) {

            StringBuilder strBul = newStringBuilder();

           strBul.Append("<option value='wangtao'>");

            strBul.Append(context.Request.Params["type"].ToString());

           strBul.Append("</option>");

           context.Response.ContentType = "text/html";

           context.Response.Write(strBul.ToString());

        }

        public bool IsReusable {

            get {

                returnfalse;

            }

        }

    }

    虽然很简单,但可以供大家举一反三。

  • 相关阅读:
    对象
    函数3
    函数2-作用域
    事件的分类
    函数1
    简单了解JSON Web令牌(JWT)
    Pycharm激活码,2020年9月29日最新激活码
    Python基础学习之常用模块
    python详细图像仿射变换讲解
    Python如何快速复制序列?
  • 原文地址:https://www.cnblogs.com/Rising/p/3013328.html
Copyright © 2011-2022 走看看