$ .ajax与$ .post相比

Jac*_*ack 1 ajax jquery

我注意到在尝试以JSON格式发布表单数据时,以下操作不起作用:

 $.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);
       }
Run Code Online (Sandbox Code Playgroud)

但是,这有效:

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

这只是好奇心,但有谁知道为什么?有没有理由使用一个而不是另一个?

fyr*_*fyr 6

  • $ .post仅用于发出HTTP Post请求.在内部,它使用$ .ajax和一组特殊参数.
  • $ .ajax可用于执行任何类型的HTTP请求,具有更大的灵活性

另见:http://api.jquery.com/jQuery.post/

$ .post相当于:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
Run Code Online (Sandbox Code Playgroud)

因此,方法调用的唯一区别是contentType.这意味着你试图基本上将两个方法调用与一组不同的参数进行比较.