2

我正在尝试在 asp.net mvc 3 中执行 ajax get 请求。它不起作用,即 GetSquareRoot 操作未命中?

索引.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);
}
4

4 回答 4

1

不确定这是否有帮助,但文档声明类型参数应该读取GET......不是Get

于 2012-04-30T11:30:21.283 回答
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

你确定你已经告诉我们整个故事了吗?

于 2012-04-30T12:29:59.727 回答
0

我认为你的 jQuery ajax 很好。但我发现你的按钮标签是错误的。

原样

<button onclick="calculateSquareRoot(9);">Calculate Square</button>

成为

<button type="button" onclick="calculateSquareRoot(9);">Calculate Square</button>

希望它会帮助你。

卢克。

于 2012-04-30T11:25:01.150 回答
0
  1. 在网络选项卡的开发人员工具(F12)中检查请求。看看会发生什么,如果它使用参数进入正确的控制器/动作
  2. 将数字类型更改为 int 而不是 long(也许 ModelBinder 难以绑定到 long(不太可能)
  3. 向 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 */ }
        });
    
于 2012-04-30T12:32:28.760 回答