Loading

ASP.NET WebForm Ajax请求Handler的经验

ajax代码

 $.ajax({
                    type: "GET",
                    url: "/AjaxHandler/GetPluginCode.ashx",
                    data: "templateid=" + templateid + "&templatepath=<%=templatePath%>&shopgroupid=" + $("#hidShopGroupID").val(),
                    cache: false,
                    success: function (msg) {
                        var results = JSON.parse(msg);
                        if (results.Key == "success") { 
                              var result = results.Value;
               }
            }
})

    原则:利用对象来判断返回结果的状态(以前用字符串分割来处理,会有问题)

Handler代码

    定义输出对象

  public class JsonObj
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }

  初始化结果变量

JsonObj _result = new JsonObj() { Key = "failure", Value = string.Empty };

  修改结果状态

try
{
   //逻辑代码
   _result.Key = "success";
   _result.Value = “htmlCode”;
}

  异常捕获

 catch (Exception ex)
 {
       _result.Value = ex.Message;
 }

  最后序列化输出

 JavaScriptSerializer se = new JavaScriptSerializer();
 context.Response.Write(se.Serialize(_result));

  原则:无论如何必须有输出,也就是要有客户端收到结果才能判断请求状态

 

posted @ 2017-08-08 17:04  shihao316558512  阅读(439)  评论(0编辑  收藏  举报