网上看了很多是用Handler1.ashx 这个文件
建立了这个文件看了下这里该怎么能声明一些方法呢。。namespace GooniuTravel
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Handler1 : IHttpHandler
    {        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}默认是这样的。再写个方法是直接在public class Handler1 : IHttpHandler {}里写么,它里边的IsReusable是干什么的呢。而且JQ有个  type : "get",  url : "/ws/NameExist.aspx",   datatype : "json",  这几个属性。
type处我是写get还是post呢~~根据什么来定这个传输模式呢
还有这个url里我要是写很多方法他怎么知道该调那个方法呢,还是说这个ashx 文件里只能写一个方法,做一个功能呢
还有这个datatype 数据类型,ashx 文件默认返回的是json么??如果不是的话,需要数据转化么??
有没有详细的例子么对于JQ的AJAX的方法。。

解决方案 »

  1.   

    但是不知道该传些什么参数额用ashx 的话JQ得那type , url , datatype 该怎么写。。
    或者您那里有示例么
      

  2.   

    autocomplete.ashx相关:public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";        string codeViewUrl = "CodeView.aspx?id=";
            string key = Convert.ToString(context.Request.QueryString["key"]);
            StringBuilder content = new StringBuilder();
            content.Append("[");
            IList<CodeInfo> codeList = Code.SelectRecords(1, 10);
            if (codeList.Count > 0)
            {
                int index = 0;
                foreach (CodeInfo codeInfo in codeList)
                {
                    index++;
                    codeViewUrl += codeInfo.CodeId.ToString();
                    if (index == codeList.Count)
                    {
                        content.Append("{title:\"" + codeInfo.Title + "\",url:\"" + codeViewUrl + codeInfo.CodeGuid + "\"}");
                    }
                    else
                    {
                        content.Append("{title:\"" + codeInfo.Title + "\",url:\"" + codeViewUrl + codeInfo.CodeGuid + "\"},");
                    }
                }
            }
            content.Append("]");        context.Response.Write(content.ToString());
        }$.ajax({ 
                            type:"GET", 
                            url:"autocomplete.ashx",
                            cache:false,
                            data:"key="+encodeURIComponent(_val),
                            beforeSend:ajaxLoading(),
                            success:function(msg){ ajaxSuccess(msg); }
                        });
    类似这样,此例子是我的autocomplete,你可以参考。
      

  3.   

    首先,创建一个aspx页面,如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jsonPost.aspx.cs" Inherits="jsonPost" %><!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>jQuery JSON 测试</title>
        <script language="javascript" type="text/javascript" src="Lib/jQuery-1.3.2/jquery-1.3.2.min.js"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready( function() {
                $("#btnSubmit").click( function() {
                    $.post ( 
                        "jsonResponse.ashx",
                        {
                            id:       $("#txtId").val(), 
                            name:     $("#txtName").val(), 
                            property: $("#txtProperty").val() 
                        },
                        function(data) {
                            alert(data);
                        }
                    );
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            输入标识:<input id="txtId" type="text" /><br /><br />
            输入名称:<input id="txtName" type="text" /><br /><br />
            输入属性:<input id="txtProperty" type="text" /><br /><br />
            <input id="btnSubmit" type="button" value="Submit" />
        </div>
        </form>
    </body>
    </html>
    注意这里要引用jquery。
      

  4.   

    其次,创建一个ashx文件,如下:<%@ WebHandler Language="C#" Class="jsonResponse" %>using System;
    using System.Web;using System.Web.Configuration;
    using System.Data.SqlClient;
    using System.IO;public class jsonResponse : IHttpHandler {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/plain";
            
            string id = context.Request["id"].ToString();
            string name = context.Request["name"].ToString();
            string property = context.Request["property"].ToString();
            
            //using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["sunpatransConnectionString"].ConnectionString))
            context.Response.Write("来自服务器的信息:\n提交的结果是:" + id + " " + name + " " + property);
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    }
      

  5.   

    这里要注意的是,实现aspx页面发送数据到服务器上,我采用了jquery。当数据发送到服务器,ashx文件负责接收,并且返回一个Response,aspx页面的jquery代码负责接收该响应,然后调用回调函数,用alert显示出来。
      

  6.   

    是用ashx都是GET传输么,post的不是更安全么,还有这个data这个里。。是个什么类型额。。
    额。还有ashx这个文件里。。只能写一个方法实现么。。看到这个JQ代码里没指名ashx文件里的方法名称,
    还有ashx返回的数据类型貌似是拼的json额。而且是个void的方法,没有返回值的可以这么传过去么,没注明返回值的话,jq那边。怎么接收数据类型呢。。
    还有$.ajax这个事件是页面嘛时候发生的,可以写在一个方法里边有个$.ajax这个么
      

  7.   

    发送请求的方式是get和post,post带参数,get不带参,ashx不管是啥,只要接收到请求        string id = context.Request["id"].ToString();
            string name = context.Request["name"].ToString();
            string property = context.Request["property"].ToString()就能处理这些数据,并用Response发送响应,然后页面端的jquery才能接收到数据。建议去学学jquery
      

  8.   

    嗷。。就是ashx里边不能再写别的方法了,想多出运用只能是在ProcessRequest这个方法里根据传来的值在方法里逻辑判断该执行那些方法了呗,
    jq这个现在也只是做点动画效果而已。。数据的调用还没用呢。。确实需要学习额。。
      

  9.   

    使用了aspx页面+jquery+ashx文件,能够很方便的实现无刷新的页面提交,那么在ProcessRequest()方法里可以实现数据库的增删改查,这相当方便。当然也许还有更方便的方法,但是目前对于我来说,这是最方便的方法了
      

  10.   

    谢谢这么耐心的指导。。分肯定给你了。。
    只是再问个问题最后一个。。
    我看有人这么写。。$("#accounts").formValidator({onshow:"请输入用户名",onfocus:"用户名至少4个字符,最多10个字符",oncorrect:"该用户名可以注册"}).inputValidator({min:4,max:10,onerror:"用户名至少4个字符,最多10个字符"}).regexValidator({regexp:"username",datatype:"enum",onerror:"用户名格式不正确"})          .ajaxValidator({          type : "get",          url : "/ws/NameExist.aspx",         datatype : "json",          success : function(data){                 if( data == "1" )              {                  return true;             }              else             {                  return false;              }          },          buttons: $("#submit"),          error: function(){alert("服务器没有返回数据,可能服务器忙,请重试");},           onerror : "该用户名不可用,请更换用户名",          onwait : "正在对用户名进行合法性校验,请稍候..."     }) 他这个是直接传了那个Url并没有再给出传递的参数了,是因为那个方法不用传值的过么
      

  11.   

    正好最近在搞这个<script type="text/javascript" language="javascript" src="js/jquery-1.5.1.min.js"></script>
    在前台写出请求代码:
    <script language="javascript" type="text/javascript">
            function GetClientInfo() {
                var RepairNo = $.trim($("#txtRepairsNo").val());            if (RepairNo.length == 0) {
                    return false;
                }
                $.get("../ashx/Handler.ashx?strRepairNo=" + RepairNo, function(data) {
                    if (data != "") {
                        var arrInfo = data.split(',');
                        $("#txtSMM_UNIT_ID").val(arrInfo[0]);
                        $("#txtSMM_UNIT_MODEL").val(arrInfo[1]);
                        $("#txtClientName").val(arrInfo[2]);
                        $("#txtSMM_LINKMAN").val(arrInfo[3]);
                        $("#txtSMM_TEL").val(arrInfo[4]);
                        $("#txtSMM_PROJECT_NAME").val(arrInfo[5]);
                        $("#txtSMM_DESCRIPTION").val(arrInfo[6]);
                        $("#txtServerMan").val(arrInfo[7]);
                    }
                });
            }
      </script> 
    <%@ WebHandler Language="C#" Class="Handler" %>
    sing System;
    using System.Collections.Generic;
    using System.Web;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using GarageWebService;<script type="text/javascript" language="javascript" src="js/jquery-1.5.1.min.js"></script>
    public class Handler : IHttpHandler {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/plain";        if (context.Request.HttpMethod == "GET")
            {
                string strNo = context.Request.QueryString["strRepairNo"].ToString();
                if (!string.IsNullOrEmpty(strNo))
               {
                  
       GarageWebService.TYMics2CarInfo GetFristTaskinfo = new GarageWebService.TYMics2CarInfo();
                   DataTable dt =GetFristTaskinfo.GetFristTaskInfo(strNo);
                     if (dt == null)
                     {
                         context.Response.Write("<script>alert('取到的值为空!');</script>");
                     }
                     else
                     {
                         DataRow row = dt.Rows[0];
                         context.Response.Write(row["vehicleNumber"].ToString() + "," + row["vehicleTypeNumber"].ToString() + ","+ row["people"].ToString() + ","
                         + row["person"].ToString() + "," + row["phone"].ToString() + "," + row["bulletinRepair"].ToString() + ","
                         + row["bulletinRepair"].ToString() + "," +row["operationName"].ToString());
                     }
               }
            }
            
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }} 
      

  12.   

    $.ajax({ 
                            type:"GET", 
                            url:"autocomplete.ashx",
                            cache:false,
                            data:"key="+encodeURIComponent(_val),
                            success:function(msg){ ajaxSuccess(msg); }
                        });ashx需要返回数据给客户端,默认的不是json格式
      

  13.   


          ///获取导出Excel数据 
        this.GetDataToExcel=function(){
           $.ajax({ 
           type:"POST",
            async: false,       
            url:"ajax.axd",
            // dataType:"json",
            data:"flag=GetDataHLTCenterToExcel&dtBegin="+Config.DtStart+"&dtEnd="+Config.DtEnd,
            beforeSend:function(){},
            error:function(txt){},
            success:function(txt){
               
               $("#ToExcelContainer").html(txt);
               
               }
          });
        }
      

  14.   

    你这个axd又是个什么类型文件额。。data这个属性这个意思是嘛意思嘞,为什么不用写dataType了呢
      

  15.   

    楼主可以先看我写的代码,把jquery的提交代码看懂以后再来看其他人写的,其他同仁写的是采用了带验证的ajax()方法,因为ajax()是get()和post()方法的底层实现,配置上要比get和post复杂。
      

  16.   


    GET或POST,看你自己需求,并分别修改后台接受方式DATA是传参数ashx的ProcessRequest方法里面你可以写多个不同的操作或调用BLL多个方法
    而且是个void的方法,没有返回值的可以这么传过去么,没注明返回值的话,jq那边。怎么接收数据类型呢。。  这个就不解释了,你去多了解下ashx和js ajax的原理吧。json拼接和我有我的原因,你可以换成别的方式,ajax方法什么时候调用看你自己需求,而且我这个是我项目中一个部分,仅仅作为浏览参考。