MVC2-5 antiforgerytoken в чистом javascript, а не в JQUERY
Я хочу закодировать это на чистом JavaScript, пожалуйста? Это работает для JQUERY1-2. Примечание: не ищу MVC Core 1+
var sMVCParameter1 = "1"; var sMVCParameter2 = "2"; var sToken = document.getElementsByName("__RequestVerificationToken")[0].value; $.ajax({ url: "/Home/ClickCreateAccount/", type: "POST", contentType: "application/x-www-form-urlencoded", data: { '__RequestVerificationToken': sToken, 'sMVCParameter1': sMVCParameter1, 'sMVCParameter2': sMVCParameter2 } }) .done(function (data) { //Process MVC Data here }) .fail(function (jqXHR, textStatus, errorThrown) { //Process Failure here });
Что я уже пробовал:
==========================================================
JavaScript может выглядеть следующим образом
==========================================================
<script type="text/javascript"> function Test_JS_Ajax() { var sToken = document.getElementsByName("__RequestVerificationToken")[0].value; var xmlHttp; //Let us create the XML http object xmlHttp = null; if (window.XMLHttpRequest) { //for new browsers xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { var strName = "Msxml2.XMLHTTP" if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) { strName = "Microsoft.XMLHTTP" } try { xmlHttp = new ActiveXObject(strName); } catch (e) { alert("Error. Scripting for ActiveX might be disabled") return false; } } if (xmlHttp != null) { //Handle the response of this async request we just made(subscribe to callback) xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var data = JSON.parse(xmlHttp.responseText); alert(data); } } xmlHttp.onerror = function () { //Not Connected } //Pass the value to a web page on server as query string using XMLHttpObject. //VERSION 1 TESTED FAILED //xmlHttp.open("GET", "/Home/Test/?sString1=" + "1", true); //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken); //xmlHttp.send(); //VERSION 2 TESTED FAILED //xmlHttp.open("GET", "/Home/Test/", true); //xmlHttp.setRequestHeader("Content-type", "application/json"); //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken); //xmlHttp.send(JSON.stringify({ "sString1": "1" })); //VERSION 3 TESTED FAILED //xmlHttp.open("GET", "/Home/Test/", true); //xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //xmlHttp.setRequestHeader("__RequestVerificationToken", sToken); //xmlHttp.send(JSON.stringify({ "sString1": "1" })); //VERSION 4 TESTED FAILED xmlHttp.open("GET", "/Home/Test/", true); xmlHttp.setRequestHeader("__RequestVerificationToken", sToken); xmlHttp.send(JSON.stringify({ "sString1": "1" })); } else { //Browser not supported! Please update your browser! } } </script>
Код C# выглядит следующим образом
[ValidateAntiForgeryToken] public JsonResult Test(string sString1) { return Json("T", JsonRequestBehavior.AllowGet); }
HTML
<body onload="Test_JS_Ajax()">