.net中使用Ajax

在.net中使用Ajax传递数据的话,一般使用ashx或asmx作为后台的处理文件,那么这2种文件在使用时有何区别呢。

1.使用ashx处理

用ashx时,在后台取参数时一般都是使用HttpContext.Request.Param["参数名"]来获取参数的,如果想多个ajax调用同一个ashx的话,可以在参数里加上比如optype的值来表示该调用哪个方法。

前端方法

<script language="javascript" type="text/javascript">
	$(document).ready(function () {
		$.ajax({
			url: "ashxtest1.ashx",
			type: "post",
			/*注意这里是json对象,ajax会将其转换成optype=add的格式,这样在后台就可以使用context.Request.Params["optype"]获取值了。
			如果这里是一个字符串的话那么后台需要使用context.Request.Params[0]来获取值,不方便使用,最好还是传入json对象便于后台获取传入的参数。
			如果需要传入较复杂的参数的话,可以这样data: { "optype": "add","param":Json.stringfy({"name":"wang","year":26}) }后台获取到param后
			可以使用反序列话插件将字符串转换为对象比如LitJson或Newtonsoft
			*/
			data: { "optype": "add", "param": JSON.stringify({ "name": "wang", "year": 26 }) },
			/*这个设置是告诉ajax在获取到返回值,将返回值转化成什么格式,如果转换失败则会进入error
			*/
			dataType: "json",
			/*contentType代表使用什么格式将数据从前端发送到服务器,比如text/plain,text/html,text/xml,text/javascript,application/json
			contentType不设置,Ajax默认会用application/x-www-form-urlencoded,适合大多数使用情况了
			对于上面常用的5种方式,这种data格式都没有问题,所以可以设置也可以不设置
			*/
			contentType: "application/json; charset=utf-8",
			success: function (returnData) {
				alert('success');
			},
			error: function (e, r, t) {
				//error的话这里会有3个参数传进来
				alert('error');
			},
			complete: function () {
				//不管是访问成功或失败都会调用此方法
			}
		});
	});
</script>
后台方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxAshx.Test
{
    /// <summary>
    /// ashxtest1 的摘要说明
    /// </summary>
    public class ashxtest1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string strOpType="";
            //ajax中如果data为json对象可以这样获取到参数
            if (context.Request.Params["optype"] != null)
            {
                strOpType = context.Request.Params["optype"].ToString();
            }
            //ajax中如果data为字符串的话需要通过index获取参数,不方便使用
            strOpType = context.Request.Params[0].ToString();

            //返回这个的话,由于ajax的dataType=json,所以会在返回值后转换失败,进入error方法
            //context.Response.Write("helloworld"); 
            //这个返回值可以正确的转换为json,进入success方法
            context.Response.Write("{\"word\":\"helloworld\"}");
            context.Response.Flush();
        }

        /// <summary>
        /// 这个是必须的
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

根据前面的分析使用ashx的好处是,前台传递参数使用json,后台可以比较方便的获取参数;基本不需要考虑contentType的影响;后台返回的值就是前台的得到的值。

2.使用asmx处理

前台方法

<script language="javascript" type="text/javascript">
$(document).ready(function () {
	$.ajax({
		/*使用asmx需要在url后面直接指定访问后台的哪个方法
		*/
		url: "asmxtest1.asmx/HelloWorld",
		type: "post",
		/*用asmx的话这里对data的格式就会有要求了,.net内部机制不是很清楚,应该是根据contentType会对data进行一个验证,
		验证不通过的会调用失败,下面列举了常用的几种类型
		1.contentType不设置:这时会默认使用application/x-www-form-urlencoded,这个时候data需要为一个json对象,对象中
		的key值需要与后台方法中传入参数一致,可以多但是不能少。<span style="color:#ff0000;">这种情况下后台返回值会是xml格式,使用时注意dataType的设置</span>。
		2.contentType=text/xml,data需要为一个正确格式的xml字符串
		3.contentType=application/json,data需要为一个代表json格式的字符串而不是一个json对象,比如'{"param":1}'
			或者'{"param":"{\\"name\\":\\"aa\\"}"}'这种复杂格式注意里面需要双斜杠。<span style="color:#ff0000;">这种情况后台返回值为json格式,会将
			返回的值放在一个d的对象里面</span>
		*/
		data: '{"param":"{\\"name\\":\\"aa\\"}"}',
		//data: { param: JSON.stringify({ "name": "aa" }) },
		dataType: "json",
		contentType: "application/json; charset=utf-8",
		success: function (returnData) {
			alert('success');
		},
		error: function (e, r, t) {
			//error的话这里会有3个参数传进来
			alert('error');
		},
		complete: function () {
			//不管是访问成功或失败都会调用此方法
		}
	});
});
</script>
后台方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace AjaxAshx.Test
{
    /// <summary>
    /// asmxtest1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    //这里一定注意要去掉注释
    [System.Web.Script.Services.ScriptService]
    public class asmxtest1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string param)
        {
            return "{\"flag\":1}";
        }
    }
}

使用asmx的话需要特别注意contentType的设置,还有对返回值的处理。综合比较,如果没有特殊要求一定要用asmx的话,使用ashx会比较简单点。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值