纯javascript中的MVC2-5 antiforgerytoken不是JQUERY [英] MVC2-5 antiforgerytoken in pure javascript not JQUERY

查看:69
本文介绍了纯javascript中的MVC2-5 antiforgerytoken不是JQUERY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用纯JavaScript编写代码吗?这适用于JQUERY1-2。注意:不寻找MVC Core 1+

I'm looking to code this in pure JavaScript please? This works for JQUERY1-2. Note: Not looking for 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可能会是这样的

=========================== ===============================



What I have tried:

==========================================================
The JavaScript Might Look like this
==========================================================

<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#代码看起来像


C# Code looks like

[ValidateAntiForgeryToken]
public JsonResult Test(string sString1)
{
   return Json("T", JsonRequestBehavior.AllowGet);
}



Html


Html

<body onload="Test_JS_Ajax()">

推荐答案

.ajax({
url:/ Home / ClickCreateAccount /,
type: POST,
contentType:application / x-www-form-urlencoded,
data:{'__ RequestVerificationToken':sToken,'sMVCParameter1':sMVCParameter1,'sMVCParameter2':sMVCParameter2}
})
.done(函数(数据){
//处理MVC数据这里
})
.fail(函数(jqXHR,textStatus,errorThrown){
//处理失败这里
});
.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可能会是这样的

======= ================================================== =



What I have tried:

==========================================================
The JavaScript Might Look like this
==========================================================

<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#代码看起来像


C# Code looks like

[ValidateAntiForgeryToken]
public JsonResult Test(string sString1)
{
   return Json("T", JsonRequestBehavior.AllowGet);
}



Html


Html

<body onload="Test_JS_Ajax()">


var sMVCParameter1 = "1";
var sMVCParameter2 = "2";
var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;

var body = new URLSearchParams();
body.append("__RequestVerificationToken", sToken);
body.append("sMVCParameter1", sMVCParameter1);
body.append("sMVCParameter2", sMVCParameter2);

fetch("/Home/ClickCreateAccount/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: body
})
.then(function(response) { 
    if (response.ok) {
        return response.json(); 
    }
    
    throw new Error('Network response was not ok.');
})
.then(function(data){
    // Process MVC data here
})
.catch(function(error){
    // Process failure here
});



使用Fetch - Web API | MDN [ ^ ]



如果您需要支持Internet Explorer,则需要两个polyfill:

GitHub - github / fetch:一个window.fetch JavaScript polyfill。 [ ^ ]

GitHub - WebReflection / url-search -params:用于URLSearchParams标准的简单polyfill [ ^ ]


Using Fetch - Web APIs | MDN[^]

If you need to support Internet Explorer, you'll need two polyfills:
GitHub - github/fetch: A window.fetch JavaScript polyfill.[^]
GitHub - WebReflection/url-search-params: Simple polyfill for URLSearchParams standard[^]


我找到了一种适用于所有浏览器并在下面测试的方法。如果您有以下任何代码更新,请告诉我们。谢谢。



I found a way that works in all browsers and tested below. If you have any code updates to below let me know thank you.

var xmlHttp = null;
if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"];
    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xmlHttp = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
}
if (xmlHttp != null) {
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById("divLOAD").style.display = "none";
            var data = JSON.parse(xmlHttp.responseText);
            if (data == "" && sIsAutoComplete == "F") {
                PlateResult("", "", "", "", "RED", sSearch);
                return;
            }
            else if (data == "") {
                return;
            }
            if (sIsAutoComplete == "T") {
                return AutoComplete(data);
            }
            else if (sIsAutoComplete == "F") {
                SearchPlateShow(data, "F");
            }
            else if (sIsAutoComplete == "A") {
                s_CacheSelectedCompanyID = s_SelectedCompanyID;
                AllData = data;
                var dt = new Date();
                CacheDate.setTime(dt.getTime() + (CacheMinutes * 60 * 1000)); //1 minute //days (exdays * 24 * 60 * 60 * 1000) || minute (exdays * 60 * 1000)
            }
        }
    }
    xmlHttp.onerror = function () {
        document.getElementById("divLOAD").style.display = "none";
        if (sIsAutoComplete == "T") {
            return AutoComplete(AllData);
        }
        else if (sIsAutoComplete == "F") {
            SearchPlateShow(AllData, "T");
        }
    }
    xmlHttp.open("POST", "/Home/SearchPlate/", true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send('__RequestVerificationToken=' + sToken + '&sLicensePlate=' + Encode(sLicensePlate) + '&sIsAutoComplete=' + sIsAutoComplete + '&sID=' + s_SelectedCompanyID + '&sKey=' + sKey + '&sIV=' + sIV);
}
else {
    //Browser not supported! Please update your browser!
    document.getElementById("spParkingTracker").innerHTML = "Browser not supported!";
}


这篇关于纯javascript中的MVC2-5 antiforgerytoken不是JQUERY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆