gpt4 book ai didi

javascript - 在 asp.net mvc 中对 Controller 进行简单的 Ajax 调用

转载 作者:IT王子 更新时间:2023-10-29 03:24:58 24 4
gpt4 key购买 nike

我正在尝试开始使用 ASP.NET MVC Ajax 调用。

Controller :

public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}

public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}

查看:

<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';

$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});

function successFunc(data, status) {
alert(data);
}

function errorFunc() {
alert('error');
}
});
</script>
</head>

我只需要打印一个带有 Controller 方法返回数据的警报。上面的代码只是在我看来打印“chamara”。警报未触发。

更新

我如下修改了我的 Controller ,它开始工作了。我不清楚为什么它现在起作用了。有人请解释一下。参数“a”与我添加它无关,因为我无法添加具有相同方法名称和参数的两个方法。我认为这可能不是解决方案,但它的工作

public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}

[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}

最佳答案

删除数据属性,因为您没有向服务器POSTING 任何内容(您的 Controller 不需要任何参数)。

并且在您的 AJAX 方法中,您可以使用 Razor 并使用 @Url.Action 而不是静态字符串:

$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});

来自您的更新:

$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});

关于javascript - 在 asp.net mvc 中对 Controller 进行简单的 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16186083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com