我正在尝试在asp.net mvc 3中执行ajax get请求。但是它没有工作,即GetSquareRoot操作没有被命中?
index.cshtml
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<script type="text/javascript">
function calculateSquareRoot(numberToCalculate) {
$.ajax({
type: 'Get',
url: '/Home/GetSquareRoot',
data: { number: numberToCalculate },
success: function (data) { alert(data.result); }
});
}
</script>
<button onclick="calculateSquareRoot(9);">Calculate Square</button>
家庭控制器上的:
public JsonResult GetSquareRoot(long number)
{
var square = Math.Sqrt(number);
return Json(new { result = square }, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
不确定这是否有帮助,但文档声明类型参数应为GET
...而不是Get
答案 1 :(得分:1)
如果我在localhost上挂载以下页面:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">
</script>
<script type="text/javascript">
//<![CDATA[
function calculateSquareRoot(numberToCalculate) {
$.ajax({
type: 'GET',
url: '/Home/GetSquareRoot',
data: { number: numberToCalculate },
success: function (data) { alert(data.result); }
});
}
//]]>
</script>
</head>
<body>
<button onclick="calculateSquareRoot(9);">Calculate Square</button>
</body>
</html>
当我点击按钮时,我看到发出的请求:
http://localhost/Home/GetSquareRoot?number=9
你确定你告诉了我们整个故事吗?
答案 2 :(得分:0)
我认为你的jQuery ajax很好。但是我发现你的按钮标签是错误的。
AS-IS
<button onclick="calculateSquareRoot(9);">Calculate Square</button>
TO-BE
<button type="button" onclick="calculateSquareRoot(9);">Calculate Square</button>
希望它会对你有所帮助。
卢克。
答案 3 :(得分:0)
向ajax调用添加错误函数:
$.ajax({
type: 'GET',
url: '/Home/GetSquareRoot',
data: { number: numberToCalculate },
success: function (data) { alert(data.result); },
error: function (jqXHR, textStatus, errorThrown) { debugger;/*see what happened */ }
});