我有一个JavaScript / jQuery函数用于执行AJAX请求,作为ASP.NET Core Razor Pages(Visual C#)项目的一部分。 AJAX请求在PageModel(.cshtml.cs)中调用它所调用的任何页面的“OnGet”处理程序方法。 AJAX请求JS / jQuery:
function conditionalDropDown(parameters) {
//code to get handler method inputs in correct format
var pathname = window.location.pathname;
var handler = "?handler=ConditionalDropDown";
var actionpath = pathname + handler;
$.ajax({
dataType: 'json',
url: actionpath,
type: 'GET',
data: {
parameterName: parameterValue
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
//dealing with the data returned by the request
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
}
PageModel中的处理程序方法:
public JsonResult OnGetConditionalDropDown(parameters)
{
//call a function to get the return string
return new JsonResult(dropdownHTML);
}
我想更改我的AJAX请求,以便它使用“OnPost”处理程序方法。我已经尝试在AJAX请求函数中将type: 'GET'
更改为type: 'POST'
,以及从OnGetConditionalDropDown
到OnPostConditionalDropDown
的处理程序方法的名称,但请求总是失败。
我将@Html.AntiForgeryToken()
添加到发送AJAX请求的页面(.cshtml)中,但我不确定它是否在正确的位置。目前,我将它放在调用AJAX请求的表单的<form>
标记内。
我想我在设置请求的方式上遗漏了一些东西,但我不知道它是什么。任何帮助是极大的赞赏。
回答我自己的问题......
beforeSend
函数,在请求初始化时替换为:headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
。type: 'GET'
更改为type: 'POST'
OnGet
- > OnPost
@Html.AntiForgeryToken()
,添加了method="post"
以形成AJAX请求现在完美运作!