About the use of Html.antiforgerytoken () in fact, many of the online explanation, such as http://blog.csdn.net/cpytiger/article/details/8781457
So what do we do with Ajax calls, and do we need to modify all of the AJAX request data? I prefer to write a generic code. The principle is simply to intercept AJAX requests and append your own data. Note that when Ajax transmits data, it can be string/. Object, so here's what you need to deal with:
if (typeof data!== "string") {
data = $.param (data);
}
In general, we intercept the specified method in the Ready method:
var Oldajax = $.ajax; $.ajax = function () {var len = arguments.length; for (var i = 0; i < len; i++) {var data = Arguments[i].data; var type = $.trim (Arguments[i].type); Type = Type.tolowercase (); if (data && type== "post") {var tokenstr = $ (Document.getelementsbyname ("__requestverificationt Oken ")). Val (); if (typeof data!== "string") {data = $.param (data); } data = data + "&__requestverificationtoken=" + tokenstr; Arguments[i].data = data; }} oldajax.apply (null, arguments); }
All JS code is as follows:
$ (function () {var oldajax = $.ajax; $.ajax = function () {var len = arguments.length; for (var i = 0; i < len; i++) {var data = Arguments[i].data; var type = $.trim (Arguments[i].type); Type = Type.tolowercase (); if (data && type== "post") {var tokenstr = $ (Document.getelementsbyname ("__requestverificationt Oken ")). Val (); if (typeof data!== "string") {data = $.param (data); } data = data + "&__requestverificationtoken=" + tokenstr; Arguments[i].data = data; }} oldajax.apply (null, arguments); } $ (' #btn1 '). Click (function () {$.ajax ({type: "POST", url: "Home/securit Ypost ",//Data:" Name=john&location=boston ", data: {" name ":" John ","Location": "Boston"}, Success:function (msg) {alert ("Data Saved:" + msg); } }); }); });
Html.antiforgerytoken () AJAX applications to prevent CSRF attacks