JSON结果只包含一个项目

max*_*dbe 0 javascript asp.net-mvc json

我可能错过了json和javascript的东西.

[{"commentText":"Testing 123","userPosted":"maxfridbe"},
{"commentText":"Testing 23","userPosted":"maxfridbe"}]
Run Code Online (Sandbox Code Playgroud)

有时候,我会得到多个与此代码一致的响应:

function(data) 
        {
            var sel = this;

            jQuery.each(data,
                function()
                {
                    sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
                });          
        };
Run Code Online (Sandbox Code Playgroud)

有时我只得到一个违反上述代码的响应:

[{"commentText":"another test again welcom","userPosted":"maxfridbe"}]
Run Code Online (Sandbox Code Playgroud)

我知道这是因为响应的处理方式与列表不同.

寻找答案,我得到了一些解决方法.任何解决方案将不胜感激.

CMS*_*CMS 7

在你提供的第二个例子中,它似乎只是一个只有一个项目的数组,如果是这样,它应该可以工作,但我认为你只得到一个像这样的对象:

{"commentText":"another test again welcom","userPosted":"maxfridbe"}
Run Code Online (Sandbox Code Playgroud)

如果是单个对象,则$.each迭代对象属性.

您可以检查您的data变量是否不是使用的数组$.isArray,如果不是,您可以将其包装到单个元素数组中,因此该$.each函数仍将按预期工作:

//..
if (!jQuery.isArray(data))  data = [data]; // if isn't an array, wrap it

jQuery.each(data, function() {
  sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
});
//..
Run Code Online (Sandbox Code Playgroud)