I'm reviewing some code for a colleague and while there's nothing inherently wrong with the jQuery Ajax calls I'm looking at, I would like to be more certain about what should and should not appear in a normal Ajax call to an ASP.Net MVC controller action.
For example, in the following code:
$(function() {
$.ajax({
url: "/Controller/action",
type: "POST",
data: ({ myObjectOrParameters }),
success: function(data) { alert(data); }
});
});
Is this pattern just fine as-is, or are there other things that should also be there? Is contentType advisable? What about dataFilter? Is that unnecessary since we aren't using Microsoft Ajax and aren't concerned about the ".d" that it returns, should I even worry?
What about the type? Is it best practice to use "GET" or even "PUT" when reading or updating information, or is "POST" the most appropriate to use in every case?
Is it more appropriate to use $.ajaxSetup in every case, or can we get away with explicitly defining our arguments each time?
I would prefer seeing the $.post() method used in this case. Unless you're using the more esoteric options in $.ajax(), I don't see any reason to use it when there are shorter and more succinct methods available:
$.post("/Controller/action", { myObjectOrParameters }, function(data) {
alert(data);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With