一种标准的AJAX提交方式

作者:互联网   出处:控件中国网   2014-11-05 19:05:02   阅读:1

一种标准的AJAX提交方式

下面要说的就是BlogEngine这个项目中的一个小小的亮点

在webform开发中,我们经常会用到AJAX向后台提交数据,在我的公司,通常是提交到本页的后台去处理,或者是webservice,这两种方法都很简便,但是总显得略混乱。

今天在看BlogEngine的时候,发现它是这样处理的

首先用一个AjaxHelper.aspx页面处理全部的ajax请求,这个页面的后台全部是:

[WebMethod]
        public static JsonResponse SavePage(
            string id,
            string content,
            string title,
            string description,
            string keywords,
            string slug,
            bool isFrontPage,
            bool showInList,
            bool isPublished,
            string parent)
        {
            WebUtils.CheckRightsForAdminPagesPages(false);

            var response = new JsonResponse { Success = false };
            var settings = BlogSettings.Instance;

            if (string.IsNullOrEmpty(id) && !Security.IsAuthorizedTo(Rights.CreateNewPages))
            {
                response.Message = "Not authorized to create new Pages.";
                return response;
            }


….

的WebMethod,这样其实和webservice没有本质的区别,只是比webservice更加清爽

再看看前台是如何处理的:

var dto = {
                       "id": Querystring('id'),
                       "content": content,
                       "title": title,
                       "desc": desc,
                       "slug": slug,
                       "tags": tags,
                       "author": author,
                       "isPublished": isPublished,
                       "hasCommentsEnabled": hasCommentsEnabled,
                       "cats": cats,
                       "date": date,
                       "time": time
                   };

                   //alert(JSON.stringify(dto));

                   $.ajax({
                       url: "../AjaxHelper.aspx/SavePost",
                       type: "POST",
                       dataType: "json",
                       contentType: "application/json; charset=utf-8",
                       data: JSON.stringify(dto),
                       success: function (result) {
                           var rt = result.d;
                           if (rt.Success) {
                               if (rt.Data) {
                                   window.location.href = rt.Data;
                               } else {
                                   ShowStatus("success", rt.Message);
                               }
                           }
                           else
                               ShowStatus("warning", rt.Message);
                       }
                   });

一个标准化的AJAX提交处理机制,要比随意的滥用好的多。
 

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat