我试图通过mvc中的JsonResult从服务器返回数据。但是由于一些奇怪的原因,我无法拿起我的代码默默地失败。客户端的第一个警报成功,我确实看到输出“Got Here”但第二个警报从未显示。为什么呢?
//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);
});
});
});
答案 0 :(得分:2)
默认情况下,MVC2 +中的JsonResult会拒绝HTTP GET请求,因此您的代码也可能存在问题。您是否尝试直接从浏览器浏览“/ Home / GetWeightsData”操作?
尝试:
return this.Json(db.WeightMearsures.Select(x => new { Day =x.Date.ToString(), Weight = x.Weight }), JsonRequestBehaviour.AllowGet);
原因就在这里 http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior%28VS.100%29.aspx
答案 1 :(得分:1)
我不确定但是在访问json时你必须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);
}
答案 2 :(得分:0)
您是否使用过Firebug来查看控制器方法的内容?那linq表达式对我来说似乎很奇怪(并且对象拼写错误)但是你确定你得到了数据并且不仅仅是没有什么可以回来的吗?
答案 3 :(得分:0)
添加.error函数以查看调用是否存在问题。
答案 4 :(得分:0)
而不是$.getJSON()
,请尝试$.ajax()
- 添加错误处理程序
$.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);
}
});