gpt4 book ai didi

jquery - Javascript 和 MVC 返回类型

转载 作者:行者123 更新时间:2023-12-01 03:52:41 26 4
gpt4 key购买 nike

我在 ASP.Net MVC 项目的页面中有此 JavaScript:

function showAllianceMembers_onclick() {
var strName = $("#allianceNameTextBox").val();

$.ajax(
{
type: "POST",
url: "/Alliance/Index",
data: "allianceName=" + strName,
success: function (result) {
if (result.success) {
alert("done!");
}
else {
alert("error!!");
}
},
error: function (req, status, error) {
alert(error);
}
});
}

如您所知,此脚本正在调用 MVC Action。这是 MVC 操作:

[HttpPost]
public ActionResult Index(string allianceName)
{
//Populating an object containing a list (IList)

return View(res);
}

这里的问题是 JavaScript 代码只显示带有错误消息的警报...我的代码有什么问题?

最佳答案

在您的 Controller 操作中,您不会发送 JSON,而是发送一个简单的 View 。因此 result 变量上没有定义 .success 属性。您的 AJAX 请求如下所示:

$.ajax({
type: "POST",
url: "/Alliance/Index",
data: { allianceName: strName },
success: function (result) {
// If you got so far the AJAX request succeeded, the result variable
// will contain the final HTML of the rendered view
alert("done!");
},
error: function (req, status, error) {
alert(error);
}
});

或者如果您想从 Controller 操作发送 JSON:

[HttpPost]
public ActionResult Index(string allianceName)
{
// populate the result
return Json(new { success = true, result = res });
}

然后:

$.ajax({
type: "POST",
url: "/Alliance/Index",
data: { allianceName: strName },
success: function (result) {
if (result.success) {
// do something with result.res
alert("done!");
}
},
error: function (req, status, error) {
alert(error);
}
});

关于jquery - Javascript 和 MVC 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557741/

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