【问题标题】:$.getJSON returning “undefined” or [object Object] [object Object]$.getJSON 返回“未定义”或 [object Object] [object Object]
【发布时间】:2013-03-07 08:02:44
【问题描述】:

我知道有些人问了同样的问题并得到了回答。我已经查看了所有这些,但我仍然无法解决我的问题。我有一个 jquery 片段,它将值发送到处理程序,处理程序处理来自 JS 的值并将数据作为 JSON 数据返回。 JSON 数据有两组记录(数据库中的两行)需要通过 getJSON 捕获并处理。 JSON 数据看起来像

[{"Name":"P1","Description":"pd1",Value":"S1Test1"},{"Name":"P1","Description":"pd1","Value":"L1Test1"}]

我的JS是

$(document).ready(function () {
    $.getJSON('ProfileHandler.ashx', { 'ProfileName': 'P1' }, function (data) {
        alert(data.Name);
    });
});

我的处理程序代码是

string ProfileName = context.Request["ProfileName"];
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = ProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(serProfileDetails);

这里的方法错误是什么?

【问题讨论】:

    标签: jquery ajax json httphandler getjson


    【解决方案1】:

    data 是一个对象数组

    data[0].name
    

    应该足以获取名字。

    要遍历整个数组,您可以执行以下操作:

    $.each(data, function(k, v){
        alert(v.name);
    });
    

    其中v 是数组中的当前对象。注意v == this

    【讨论】:

    • 你给了我比我要求的更多,谢谢伙计。
    【解决方案2】:

    您的 JSON 定义了一个 数组,其中包含对象作为条目。所以不是

    alert(data.Name);
    

    你想要

    alert(data[0].Name);
    

    (当然还有其他索引,在您的示例中,您有 01)。

    (引用的 JSON 也是无效的[在第一个 Value 之前缺少 "],但我猜这是问题中的错字。)

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2015-08-18
      • 2021-09-14
      • 2023-03-06
      • 2013-09-13
      • 2015-01-24
      相关资源
      最近更新 更多