通过Jquery获取jsonString的结果是空的
我使用的是asp mvc,我在程序的一部分中获取数据,就像这样通过Jquery获取jsonString的结果是空的,jquery,asp.net-mvc,json,linq,Jquery,Asp.net Mvc,Json,Linq,我使用的是asp mvc,我在程序的一部分中获取数据,就像这样 public List<IncidentPerAreaCount> getIncident() { int RondeboschCounter = 0; int ClaremontCounter = 0; int AthloneCounter = 0; List<IncidentPerAreaCount> IncidentAreaCou
public List<IncidentPerAreaCount> getIncident()
{
int RondeboschCounter = 0;
int ClaremontCounter = 0;
int AthloneCounter = 0;
List<IncidentPerAreaCount> IncidentAreaCount = new List<IncidentPerAreaCount>();
IncidentPerAreaCount Rondebosch = new IncidentPerAreaCount();
IncidentPerAreaCount Claremont = new IncidentPerAreaCount();
IncidentPerAreaCount Athlone = new IncidentPerAreaCount();
List<Report> Reports = GetReports();
for (int i = 0; i < Reports.Count(); i++)
{
if (Reports.AsEnumerable().ElementAt(i).Area == "Rondebosch")
{
RondeboschCounter++;
}
else if (Reports.AsEnumerable().ElementAt(i).Area == "Claremont")
{
ClaremontCounter++;
}
else if (Reports.AsEnumerable().ElementAt(i).Area == "Athlone")
{
AthloneCounter++;
}
}
Rondebosch.AreaName = "Rondebosch";
Rondebosch.NumberOfIncidents = RondeboschCounter;
Claremont.AreaName = "Claremont";
Claremont.NumberOfIncidents = ClaremontCounter;
Athlone.AreaName = "Athlone";
Athlone.NumberOfIncidents = AthloneCounter;
IncidentAreaCount.Add(Rondebosch);
IncidentAreaCount.Add(Claremont);
IncidentAreaCount.Add(Athlone);
return IncidentAreaCount;
}
但是,警报函数一直显示为空(即空文本框),而不是带有数据的json格式字符串
请帮助…您将警报放置在错误的位置
$.ajax({
url: "Home/getIncident",
async: false,
dataType: 'json',
success: function (json) {
Reports = json.whatever;
alert(Reports); // should be here.
}
});
在开始编写代码之前,请先阅读并输入数据。您的数据是在ajax的成功函数中获得的,而不是在ajax之外。尝试在成功中移动警报,然后您将获得数据
var Reports = [];
$.ajax({
url: "Home/getIncident",
async: false,
dataType: 'json',
success: function (json) {
Reports = json.whatever;
alert(Reports); //Right place
}
});
alert(Reports); // Wrong place
我看到的第一件事是,您没有序列化要返回的对象。你可以这样做
return new JavaScriptSerializer().Serialize(your_object);
在客户端,您必须将json字符串转换为有效的Js对象,我在json响应字符串中使用“d”atribute
var theObject = $.parseJSON(response.d);
这个物体有你需要的心房
最后我看到您的对象是一个列表,您可以使用$进行迭代。每个当然可以。欢迎来到Ajax的世界,但是弹出的提醒消息框仍然是空的,对我来说是合适的地方。Async设置为false,Reports是一个范围超出jquery ajax方法的变量。如果我编写了“Reports=json”,则警报消息框中的输出为“[object object]、[object object]、[object object]。”
var theObject = $.parseJSON(response.d);