MVC3 jQuery getJSON不会发出调用

我试图使用getJSON()调用使ajax工作。 当我导航到/ Home / GetWeather时,我在浏览器中返回Json数据。 但是jQuery调用不起作用。 有任何想法吗? 当我将断点置于警报(“你好”)时,它从未命中。 在萤火虫中,我没有看到任何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 = new List(); // populate weather with data return Json(weather, JsonRequestBehavior.AllowGet); } } 

视图:

 @{ Layout = null; }    Index    $(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 :( }); }); });     

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

据我所知,你试图称之为跨域。 让代码用完网站的域名。 在我使用html文件调用从localhost运行的json之前,它确实没有返回任何内容。 但是把那个html放到同一个地方,从localhost调用它你会没事的。

  • 不要使用Asp.Net-MVC硬编码URL使用Url.Action
  • 删除null参数。 为什么需要向控制器发送null ? 只是省略它。

获得正确路线的代码:

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

在脚本内:

 $("#Button1").click(function () { $.getJSON("@Url.Action("GetWeather", "Home")", function (data) { alert("Hello"); }); }); 

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

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