开发者

Jquery's function not working correct for me $.getJSON

I am trying to return data from the server via a Jso开发者_StackOverflownResult in mvc. However for some strange reason I cannot pick up my code silently fails. The first alert on the client side succeeds and I do see the output "Got Here" but the second alert is never displayed. Why?

    //Server Side
    public JsonResult GetWeightsData()
    {
          PerfomanceMeasureDBDataContext db = new PerfomanceMeasureDBDataContext();
          return this.Json(db.WeightMearsures.Select(x => new { Day =x.Date.ToString(),   Weight = x.Weight }));
    }


    //Client Side
    $(function () {
        $('#ShowChart').click(function () {
            alert("Got Here");
            $.getJSON("/Home/GetWeightsData", null, function (data) {
                alert(data[0].Day);
                var dates = new Array();
                var weights = new Array();
                for (var i = 0; i < data.length; i++) {
                    dates[i] = data[i].Day;
                    weights[i] = data[i].Weight;
                    alert(dates[i]);
                }
                showChart(dates, weights);
            });
        });
    });


HTTP GET requests are denied by default by JsonResult in MVC2+ so that could also be a problem with your code. Have you tried browsing the "/Home/GetWeightsData" action directly from a browser?

Try:

return this.Json(db.WeightMearsures.Select(x => new { Day =x.Date.ToString(),   Weight = x.Weight }), JsonRequestBehaviour.AllowGet);

The reason for it is here http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior%28VS.100%29.aspx


im not sure but while accessing json you have to JsonRequestBehavior.AllowGet

public JsonResult GetWeightsData()
{
      PerfomanceMeasureDBDataContext db = new PerfomanceMeasureDBDataContext();
      return this.Json(db.WeightMearsures.Select(x => new { Day =x.Date.ToString(),   Weight = x.Weight }),JsonRequestBehavior.AllowGet);
}


Have you used Firebug to see what's coming out of your controller method? That linq expression seems odd to me (and the object is spelled wrong) but are you sure you're getting data and it's not just that there's nothing to come back?


Add a .error function to see if there's a problem with the call.

See jQuery.getJSON docs.


Instead of $.getJSON(), try $.ajax() - add an error handler

$.ajax({
  url: '/Home/GetWeightsData',
  type: 'post', // Use post, not get
  dataType: 'json',
  success:function(){
      alert(data[0].Day);
      var dates = new Array();
      var weights = new Array();
      for (var i = 0; i < data.length; i++) {
          dates[i] = data[i].Day;
          weights[i] = data[i].Weight;
          alert(dates[i]);
      }
      showChart(dates, weights);
  },
  error:function(jqXHR, textStatus, errorThrown){
      alert(errorThrown);
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜