$ .ajax与$ .post相比

I noticed when trying to post form data in JSON format, that the following does not work:

 $.ajax({
     type: "POST",
     url: url,
     data: JSON.stringify(formData),
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(msg) {
       // TODO: Listen for server ok.
       alert(msg);
       }

But, this works:

  $.post(url,
      JSON.stringify(formData),
      function(msg) {
         // TODO: Listen for server ok. If this is successfull.... clear the form
         alert(msg);
      },
      "json");

This is just curiosity, but does anyone know why? Is there any reason to use the one instead of the other?

  • $.post is only meant for issuing HTTP Post requests. Internally it uses $.ajax with a special set of parameters.
  • $.ajax can be used to do any kind of HTTP request with more flexibility

See also: http://api.jquery.com/jQuery.post/

$.post is equivalent to:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

So the only difference in your method call is the contentType. That means you are trying to compare two method calls with a different set of parameters basically.