代码改变世界

一种标准的AJAX提交方式

2011-02-08 13:11  穆容  阅读(520)  评论(0编辑  收藏  举报

webmatrix的确是个好东西,今后找开源项目不用在上codeplex什么的了,直接从WM上Down就成,并且连设置都是自动的,微爽

下面要说的就是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提交处理机制,要比随意的滥用好的多。但是很多时候,信奉快捷的中国的开发人员总是滥用,并且不知反省