当前位置:  开发笔记 > 编程语言 > 正文

使用jQuery Ajax调用时最佳做法是什么?

如何解决《使用jQueryAjax调用时最佳做法是什么?》经验,为你挑选了2个好方法。

我正在为一位同事审查一些代码,虽然我正在查看的jQuery Ajax调用没有任何内在错误,但我想更加确定在ASP.Net的正常Ajax调用中应该和不应该出现什么MVC控制器动作.

例如,在以下代码中:

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

这个模式是不是很好,还是还有其他东西应该存在?是contentType可取?怎么样dataFilter?这是不必要的,因为我们没有使用Microsoft Ajax并且不关心它返回的".d",我是否应该担心?

怎么样type?最佳做法是在阅读或更新信息时使用"GET"甚至"PUT",还是在每种情况下最适合使用"POST"?

是否更适合$.ajaxSetup在每种情况下使用,或者我们是否可以在每次明确定义我们的论点时逃脱?



1> Sampson..:

叫我一个简洁的人......

我更希望看到$.post()这种情况下使用的方法.除非您使用更深奥的选项$.ajax(),否则当有更短且更简洁的方法时,我认为没有任何理由使用它:

$.post("/Controller/action", { myObjectOrParameters }, function(data) {
  alert(data);
});



2> smaglio81..:

如前面的帖子所述,您所做的请求类型取决于要采取的操作类型.

GET:系统的状态不应该改变(正如Kyle写的,幂等的).

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 
on your website $('#errorDiv').text(error); } }); })(jQuery);

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

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

一旦你有了基本的javascript框架,你就可以在ASP.NET MVC项目中添加类,这将返回框架所期望的数据.在上面的javascript中,_ajax函数有一个成功函数,它需要一个包含属性'result'和'message'的JSON对象.这可以通过MVC模型中的基类来实现.

using System;

/// 
/// 
/// Encapsulates the common/expected properties for the JSON results
/// on this website.
/// 
/// 
/// The  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  property should also be filled in.
/// 
/// 
public abstract class JsonResultBase
{

    #region constructors

    /// 
    /// Creates a basic  with a 'success' message.
    /// 
    public JsonResultBase()
        : this("success", string.Empty) { }

    /// 
    /// Creates a  with the  and 
    /// properties initialized. This should be used when creating a 'fail'
    /// result.
    /// 
    /// The result type: 'sucess', 'fail', or 'error'.
    /// The message which described why the result occured.
    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;
    }

    /// 
    /// Creats a  which translates an exception into
    /// an error message for display on the webpage.
    /// 
    /// The exception to send back.
    public JsonResultBase(Exception e)
    {
        this.result = "error";
        this.message = e.Message;
    }

    #endregion

    #region properties

    /// 
    /// The result of the action. This could contain the value of 'success', 'fail', or 'error'.
    /// Or, some other values that you define.
    /// 
    public string result { get; set; }

    /// 
    /// Any extra information which would be helpful to describe a result. This will always be
    /// populated if the result is not 'success'.
    /// 
    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 );
        }
    }

}

HTH

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有