【发布时间】:2013-04-17 15:43:51
【问题描述】:
我正在尝试开始使用 ASP.NET MVC Ajax 调用。
控制器:
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>
我只需要打印一个带有返回数据的控制器方法的警报。上面的代码只是在我看来打印“chamara”。没有触发警报。
更新
我如下修改了我的控制器,它开始工作。我不清楚为什么它现在可以工作。有人请解释一下。参数“a”不相关我添加了它,因为我无法添加具有相同方法名称和参数的两个方法。我认为这可能不是解决方案,而是它的工作
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
【问题讨论】:
-
返回 json 格式的字符串
{"name":"chamara"}。然后尝试阅读为data['name'] -
从视图中移除第二个 jQuery 库。您的代码应该按原样工作。我认为可能发生了脚本错误并阻止了警报显示。
标签: c# jquery asp.net asp.net-mvc asp.net-mvc-2