【问题标题】:iterating through JSON object array遍历 JSON 对象数组
【发布时间】:2013-10-28 10:15:48
【问题描述】:

这个问题已被多次询问和回答,但我无法解决。我的问题看起来像这个one,这个one 和一个third example

我想做的是从 JSON 对象中填充一个选项框,例如 thisthis 问题。它们都略有不同,但相似,但我无法让它工作。这是我来自网络服务的代码:

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function HelloWorld(ByVal p_productCategoryId As Integer) As String
    Dim productCategory = ProductService.GetProductCategory(p_productCategoryId)

    'Dim productList = ProductService.GetProducts(productCategory)
    Dim productList = New List(Of Product)
    For cnt = 1 To 3
        Dim product = New Product(cnt)
        product.Productname = cnt.ToString & "|" & cnt.ToString
        productList.Add(product)
    Next

    Return productList.ToJSON

End Function

End Class

 <System.Runtime.CompilerServices.Extension()> _
Public Function ToJSON(Of T)(p_items As List(Of T)) As String
    Dim jSearializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    Return jSearializer.Serialize(p_items)
End Function

如果我使用以下代码:

function Test() {
  $.ajax({
     type: "POST",
     url: "Service.asmx/HelloWorld",
     data: "{'p_productCategoryId' : 1 }",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success:function(msg){
        alert(msg.d)
        },
     error: function() {
      alert("An error has occurred during processing your request.");
                        }
  });

};

我得到这个结果:

[{"Id":1,"IsActive":false,"Category":null,"Productname":"1|1","Price":0},
{"Id":2,"IsActive":false,"Category":null,"Productname":"2|2","Price":0},
{"Id":3,"IsActive":false,"Category":null,"Productname":"3|3","Price":0}]

这看起来不错。

如果我从味精中删除“d”。警报中的结果是:

[object Object]

填写选项框的“正在进行中”的代码是这样的(目前:):

function Test() {
$.ajax({
    type: "POST",
    url: "Service.asmx/HelloWorld",
    data: "{'p_productCategoryId' : 1 }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        $("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select"));
        $.each(msg.d, function () {
                           $("#prd_id").append($("<option></option>").val(this['Id']).html(this['Productname']));
        });
    },
    error: function () {
        alert("An error has occurred during processing your request.");
    }
});

};

从我之前提到的示例中,我尝试了几种方法让它工作,但无济于事。使用 msg.d 使用字符串中的字符数填充选项框。我尝试使用“getJSON”从“msg”显式创建一个 JSON 对象。 (这不是“数据类型”的用途吗?)我不能使用命名对象,因为我没有你在示例数据中看到的那样。我错过了什么?

有些我无法让代码看到数组有三个条目。

【问题讨论】:

    标签: jquery asp.net .net json


    【解决方案1】:

    我可能会使用 Option 构造函数而不是 HTML。

    假设 msg.d 确实是数组(.d 属性是 ASP.Net 的东西):

    success: function (msg) {
        var options = $("#prd_id")[0].options;
        options.length = 0;
        options.add(new Option("Please select", "[-]"));
        $.each(msg.d, function () {
            options.add(new Option(this.Productname, this.Id));
        });
    },
    

    Live Example | Source

    Option 构造函数将文本作为第一个参数,将值作为第二个参数。 optionsselect 元素上的列表有点像数组,除了为了与旧版浏览器兼容,您使用push 代替push(或分配给options[options.length],两者都可以)。

    或者如果msg是数组(不是.d),就去掉.d

    success: function (msg) {
        var options = $("#prd_id")[0].options;
        options.length = 0;
        options.add(new Option("Please select", "[-]"));
        $.each(msg, function () {
            options.add(new Option(this.Productname, this.Id));
        });
    },
    

    Live Example | Source

    如果未使用正确的 MIME 类型发回您的响应,msg 实际上可能是文本,而不是数组。如果是这样,您希望通过返回正确的 MIME 类型 (application/json) 在服务器上修复它,尽管您可以手动解析它:

    msg = $.parseJSON(msg);
    

    ...然后使用上面的。或者,当然,如果它以 msg.d 的形式返回(尽管这似乎不太可能):

    msg.d = $.parseJSON(msg.d):
    

    【讨论】:

    • 从您的实时示例中,我可以看到“d”是一个命名对象。这在我来自网络服务的消息中不存在。这就解释了为什么它不起作用。在您的示例中,您使用“d”的任何方式都行不通。不过,您如此快速地创建了一个实时示例真是太棒了。
    • @Sigur:你说你通知了msg.d 并得到了那个,所以我假设msg.d 是数组(这是 ASP.Net 所做的,我一直不明白为什么)。如果msg 是数组,只需删除.d
    • @Sigur:我在上面添加了两个进一步的注释。
    • @TJ 克劳德。删除“d”正是我的想法。所以我已经这样做了。现在选项框有两行:一行“请选择”,另一行命名为“未定义”。使用下面 Palash 的代码,我可以选择很多“未定义”选项。你认为 webservice 的答案没有被正确识别吗?
    • @Sigur:听起来像。使用浏览器内置的调试器,使用success 回调在第一行设置断点,然后使用变量检查器查看msg。所有现代浏览器都内置了调试器,没有理由在黑暗中徘徊。 :-) 查看“开发工具”菜单,或者在大多数浏览器上,只需按 F12。
    【解决方案2】:

    你可以这样做:

    $.each(msg.d, function (key, value) {
        $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname));
    });
    

    Fiddle Demo

    【讨论】:

    • @Palash 查看我对上面 TJ Crowder 的回答
    【解决方案3】:

    我尝试根据您的问题使用我的 REST WCF 进行复制,它返回相同的 JSON 数据,并且下面的示例有效,

    <script type="text/javascript">
    $(document).ready(function() {
    });
    var GetRawList = function() {
        $.ajax({
            type: "GET",
            url: "RestService/HelloWorld",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function(data) {
      //Change this "data.d" According to your returned JSON output header. 
                var result = data.d;  
       $("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select"));
                $.each(result, function(key, value) {
                $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname));
                });
            },
            error: function(xhr) {
                alert(xhr.responseText);
            }
        });
    }
    

    【讨论】:

    • 我已经试过你的代码了。结果是我以前见过的:一个很长的选项列表,没有文本。如果我删除“d”,则有一个没有 tekst 的列表选项。在 TJ Crowder 的 cmets 之后,我进行了一些调查。我正在使用我的新雇主提供的自定义框架,我的任务是学习它。该框架似乎对 .asmx 相关的事情做了一些事情。为了完成这项工作,我将使用 WCF 服务并看看会发生什么。谢谢
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2017-11-10
    相关资源
    最近更新 更多