【问题标题】:ajax success call returns json list of objects - cant access propertiesajax 成功调用返回对象的 json 列表 - 无法访问属性
【发布时间】:2017-08-12 02:53:43
【问题描述】:

ResultData 是 CommandModel 对象的列表。

 [ { "Command": "Blueprint", "Count": 77 }, { "Command": "Template", "Count": 188 }, { "Command": "Test", "Count": 78 } ]     

那里返回的对象看起来像这样,

public class CommandModel
{
    public string Command {get; set;}
    public int Count {get; set;}
}       

我正在尝试使用点属性表示法访问对象数据,如本视频 (https://www.youtube.com/watch?v=7oUZXuI7OgQ) 中所述。

     $("#btn").click(function () {
            $.ajax({

                url: "http://localhost:6023/external",
                type: "GET",
                accept: "application/json",
                dataType: 'json',
                success: function (resultData) {
                    $.each(resultData, function (key, value) {
                        var command = value.command; // returns undefined
                        var count = value.count; // returns undefined
                        $("tbl").append("<tr><td>" + command + "</td><td>" + count + "</td></tr>")
                    })
                },

                error: function (e) {
                    alert("something broke");
                }
            })

在第一次迭代运行时,变量如下所示:

Key = 0
Value = Object {Command:"Blueprint", Count:77}

不确定我在这里缺少什么。

【问题讨论】:

  • Javascript 区分大小写。试试var command = value.Command;
  • @KelvinSherlock Doh,就是这样。数据现在被正确提取,但未正确存储到表中。如果这不是一件事,那是另一件事:) 请随时提交作为答案,我很乐意接受。

标签: c# ajax jscript


【解决方案1】:

您使用的是小写而不是大写。

在你的课堂上你有

public class CommandModel
{
    public string Command {get; set;}
    public int Count {get; set;}
}

所以在脚本中使用Comand 而不是comandCount中的情况相同

 $.each(resultData, function (key, value) {
                    var command = value.Command; // Change here
                    var count = value.Count; //  Change here
                    $("tbl").append("<tr><td>" + command + "</td><td>" + count + "</td></tr>")
                })

【讨论】:

    【解决方案2】:

    试试

    $.each(resultData, function (value) { ... }
    

    【讨论】:

    • 使用这个,第一次迭代值 = 0
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多