0

我正在尝试使用 getJSON() 调用使 ajax 工作。当我导航到 /Home/GetWeather 时,我会在浏览器中返回 Json 数据。但是 jQuery 调用不起作用。有任何想法吗?当我在警报(“Hello”)上设置断点时,它从未命中。在萤火虫中,我没有看到任何 ajax 调用。有任何想法吗?

$(document).ready(function() {
    $("#Button1").click(function() {
        $.getJSON("/Home/GetWeather", null, function(data) {
            alert("Hello");
        });
    });
});​

控制器代码

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetWeather()
    {
        List<Weather> weather = new List<Weather>();

        // populate weather with data

        return Json(weather, JsonRequestBehavior.AllowGet);
    }
}

看法:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#Button1").click(function () {
                $.getJSON("/Home/GetWeather", null, function (data) { //I hit breakpoint here, but in firebug I dont see any call, nothing
                    alert("Hello"); // Breakpoint here doesnt hit :(
                });
            });

        });

    </script>
</head>
<body>
    <input id="Button1" type="button" name="Button1" value="Get Weather" />
    <div id="Weather"></div>
</body>
</html>

我找到的解决方案被删除的任何原因???

4

3 回答 3

4

据我所知,您正在尝试将其称为跨域。让代码跑出站点的域。在我让 html 文件调用从 localhost 运行的 json 之前,它确实没有返回任何内容。但是把那个html放到同一个地方,从localhost调用它就可以了。

于 2012-12-13T13:08:38.753 回答
3
  • 不要Asp.Net-MVC使用硬编码 URLUrl.Action
  • 删除null参数。为什么需要发送null到控制器?只是省略它。

获得正确路线的代码:

@Url.Action("GetWeather", "Home")

脚本内部:

$("#Button1").click(function () {
    $.getJSON("@Url.Action("GetWeather", "Home")", function (data) {
        alert("Hello");
    });
});
于 2012-06-24T17:16:06.323 回答
1

如果按钮是提交按钮或锚点,请确保通过返回 false 取消按钮的默认操作:

$("#Button1").click(function() {
    $.getJSON("/Home/GetWeather", null, function(data) {
        alert("Hello");
    });

    return false; // <!-- cancel the default action of the button
});

正如@gdoron他在回答中所说,永远不要对这样的网址进行硬编码。始终使用 url 助手来生成它们。


更新:

现在您已经展示了您的视图,我可以看到您已将 url 硬编码到脚本中:

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>

你不应该这样做。您应该始终使用 url 助手:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.5.1-vsdoc.js")" type="text/javascript"></script>

此外,您应该学习使用诸如 FireBug 之类的 javascript 调试工具,这使得检测这些错误变得轻而易举。如果您使用过 FireBug,您在请求这些脚本时会看到 404 错误。

于 2012-06-24T18:02:19.460 回答