What are the best methods when using jQuery Ajax calls?

I am looking at some code for a colleague, and although I do not see anything wrong with the jQuery Ajax calls that I am looking at, I would like to be more confident that the ASP manager actions should and should not appear in a regular Ajax call. Net MVC.

For example, in the following code:

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

Is this template just perfect as it is, or are there other things that should also be there? Is it recommended contentType? What about dataFilter? Isn’t it necessary, since we don’t use Microsoft Ajax and don’t worry about the “.d” that it returns, should I even worry?

How about type? Is it better to use “GET” or even “PUT” when reading or updating information, or “POST” is most suitable for use in each case?

How appropriate is it to use $.ajaxSetupin each case, or can we leave with an explicit definition of our arguments each time?

+5
source share
3 answers

Call me a man of brevity ...

I would prefer the method to be used in this case $.post(). Unless you use more esoteric parameters in $.ajax(), I see no reason to use it when there are shorter and more concise methods:

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

, , , , .

  • GET: ( , ).
  • POST: , .

HEAD, DELETE .. RESTful (http://en.wikipedia.org/wiki/Representational_State_Transfer).

, -, javascript/ajax, javascript - jQuery. , -. , 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 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 , 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 );
        }
    }

}

+5

, GET, idempotent. ( , , ). - , . . , , , POST. Google GET POST.

Another best practice that you are missing is an error handler. This refers to server errors 500 or 403 in response to a request and is important.

+3
source

All Articles