我在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 Action
:
[HttpPost]
public ActionResult Index(string allianceName)
{
//Populating an object containing a list (IList)
return View(res);
}
这里的问题是JavaScript代码只显示带有ERROR消息的警报...... 我的代码有什么问题?
答案 0 :(得分:2)
在您的控制器操作中,您不是发送JSON,而是一个简单的视图。因此.success
变量上没有定义result
属性。以下是您的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);
}
});
或者如果您想从控制器操作发送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);
}
});
答案 1 :(得分:1)
我假设您正在尝试检索数据,而不是HTML标记 试试这个:
$.ajax(
{
type: "POST",
url: "/Alliance/Index",
data: { 'allianceName' : strName },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("done!");
}
else {
alert("error!!");
}
},
error: function (req, status, error) {
alert(error);
}
});
并更新此内容:
[HttpPost]
public JsonResult Index(string allianceName)
{
//Populating an object containing a list (IList)
return new JsonResult { Data = res };
}