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

  原則:無論如何必須有輸出,也就是要有客戶端收到結果才能判斷請求狀態

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章