代码之家  ›  专栏  ›  技术社区  ›  Phil.Wheeler

使用jQueryAjax调用时的最佳实践是什么?

  •  5
  • Phil.Wheeler  · 技术社区  · 16 年前

    我正在为一位同事复习一些代码,虽然没有什么固有的东西 对于我正在研究的jQueryAjax调用,我想更加确定在对ASP.NETMVC控制器操作的普通Ajax调用中应该出现什么和不应该出现什么。

    例如,在以下代码中:

        $(function() {
            $.ajax({
                url: "/Controller/action",
                type: "POST",
                data: ({ myObjectOrParameters }),
                success: function(data) { alert(data); }
            });
        });
    

    这种模式是正常的,还是应该有其他的东西?是 contentType 明智的那么...怎么样 dataFilter ? 既然我们不使用MicrosoftAjax,也不关心它返回的“.d”,那么这是没有必要的吗?我应该担心吗?

    那这个呢 type ? 阅读或更新信息时使用“GET”甚至“PUT”是最佳做法,还是“POST”在所有情况下都最适合使用?

    使用它更合适吗 $.ajaxSetup

    3 回复  |  直到 16 年前
        1
  •  6
  •   Community Mohan Dere    6 年前

    我更喜欢看电影 $.post() 本例中使用的方法。除非你正在使用中更深奥的选项 $.ajax() ,我看不出有任何理由在有更简短的方法可用时使用它:

    $.post("/Controller/action", { myObjectOrParameters }, function(data) {
      alert(data);
    });
    
        2
  •  6
  •   smaglio81    16 年前

    如前几篇文章所述,您提出的请求类型取决于要采取的行动类型。

    • GET:系统的状态应该是 幂等元)。
    • POST:发送数据,其中 将更新的值或状态 系统。

    其他类型的请求有HEAD、DELETE等,但在RESTful开发之外并不常用( http://en.wikipedia.org/wiki/Representational_State_Transfer

    在开发依赖javascript/ajax的网站时,我一直在使用的一种做法是在jQuery之上为网站开发自定义javascript框架。该库将处理特定于网站的常见功能。例如,您的问题是关于jQuery的ajax函数。特定于您的网站的一些常见功能可能是:显示错误消息、处理意外错误代码(500、404等)、为调用添加公共参数以及数据传输类型(JSON、XML等)。

    网站的简单自定义javascript框架可能如下所示:

    (function ($) {
        if (!window.myWebsite) { window.myWebsite = {}; }
    
        //  once myWebsite is defined in the "window" scope, you don't have
        //  to use window to call it again.
        $.extend(myWebsite, {
            get: function (url, data, callback) {
                myWebsite._ajax(url, data, "GET", callback);
            },
    
            post: function (url, data, callback) {
                myWebsite._ajax(url, data, "POST", callback);
            },
    
            _ajax: function (url, data, type, callback) {
                //  http://api.jquery.com/jQuery.ajax/
                $.ajax({
                    type: type,
                    url: url,
                    data: data,
                    dataType: 'json',
                    success: function(data, status, request) {
                        //  I'll talk about this later. But, I'm assuming that the data
                        //  object returned from the server will include these fields.
                        if( data.result == 'error' ) {
                            myWebsite._displayError( data.message );
                        }
    
                        //  if no error occured then the normal callback can be called
                        if( $.isFunction(callback) )
                            callback();
                    },
                    error: function (request, status, error) {
                        myWebsite._displayError( error );        
    
                        //  you can also use this common code for handling different
                        //  error response types. For example, you can handle a
                        //  500 "internal server error" differently from a 404
                        //  "page not found"
                    }
                });
            },
    
            _displayError: function( text ) {
                //  Many pages have a common area
                //  defined to display error text, let's call that
                //  area <div id="errorDiv" /> on your website
                $('#errorDiv').text(error);
            }
        });
    })(jQuery);
    

    您可以从页面调用自定义javascript,如下所示:

    myWebsite.get( '/Controller/Action', {}, function() { ... } );
    

    一旦基本javascript框架就绪,就可以将类添加到ASP.NET MVC项目中,该项目将返回框架预期的数据。在上面的javascript中,_ajax函数有一个success函数,它需要一个包含属性“result”和“message”的JSON对象。这可以通过MVC模型中的基类实现。

    using System;
    
    /// <summary>
    /// <para>
    /// Encapsulates the common/expected properties for the JSON results
    /// on this website.
    /// </para>
    /// <para>
    /// The <see cref="result" /> property should contain the value 'success', when
    /// all processing has gone well. If the action has either 'fail'ed or has an 'error'
    /// then the <see cref="message"/> property should also be filled in.
    /// </para>
    /// </summary>
    public abstract class JsonResultBase
    {
    
        #region constructors
    
        /// <summary>
        /// Creates a basic <see cref="JsonResultBase"/> with a 'success' message.
        /// </summary>
        public JsonResultBase()
            : this("success", string.Empty) { }
    
        /// <summary>
        /// Creates a <see cref="JsonResultBase"/> with the <see cref="result"/> and <see cref="message"/>
        /// properties initialized. This should be used when creating a 'fail'
        /// result.
        /// </summary>
        /// <param name="result">The result type: 'sucess', 'fail', or 'error'.</param>
        /// <param name="message">The message which described why the result occured.</param>
        public JsonResultBase(string result, string message)
        {
            if (result != "success" && string.IsNullOrEmpty(message))
            {
                throw new ArgumentException("message", "message must have a value when the result is not 'success'.");
            }
    
            this.result = result;
            this.message = message;
        }
    
        /// <summary>
        /// Creats a <see cref="JsonResultBase"/> which translates an exception into
        /// an error message for display on the webpage.
        /// </summary>
        /// <param name="e">The exception to send back.</param>
        public JsonResultBase(Exception e)
        {
            this.result = "error";
            this.message = e.Message;
        }
    
        #endregion
    
        #region properties
    
        /// <summary>
        /// The result of the action. This could contain the value of 'success', 'fail', or 'error'.
        /// Or, some other values that you define.
        /// </summary>
        public string result { get; set; }
    
        /// <summary>
        /// Any extra information which would be helpful to describe a result. This will always be
        /// populated if the result is not 'success'.
        /// </summary>
        public string message { get; set; }
    
        #endregion
    
    }
    

    然后可以扩展该基类以返回调用的特定数据,并在控制器中使用。

    public class HomeController : Controller
    {
    
        private class ValuesJsonResult : JsonResultBase {
            public ValuesJsonResult() : base() {}
            public ValuesJsonResult(Exception e) : base(e) {}
    
            public string[] values  = new string[0];
        }
    
        public ActionResult GetList() {
            try {
                return Json(
                    new ValuesJsonResult{ values = new [] { "Sao Paulo", "Toronto", "New York" } },
                    JsonRequestBehavior.AllowGet
                );
            } catch( Exception e ) {
                //  Opps, something went wrong
                return Json( new ValuesJsonResult(e), JsonRequestBehavior.AllowGet );
            }
        }
    
    }
    

        3
  •  4
  •   Kyle Butt    16 年前

    使用GET发出的请求应为 (也就是说,如果它们重复出现,净效应是相同的)。幂等查询的一个简单子集是那些没有副作用的查询。e、 g.搜索查询。一个好的经验法则是更新用户状态的东西应该是POST。谷歌获取更多关于GET vs POST的信息。