【问题标题】:How to Iterate through Ajax data response如何迭代 Ajax 数据响应
【发布时间】:2021-01-19 00:57:12
【问题描述】:

对于我的代码,我使用以下响应 JSON 响应

{
"command": "SELECT",
"rowCount": 2,
"oid": null,
"rows": [
    {
        "name": "Life Insurance Silver",
        "product__c": "01t2o000007pd3MAAQ"
    },
    {
        "name": "Life Insurance Gold",
        "product__c": "01t2o000007pdqpAAA"
    }
],

如何使用 Ajax 遍历此数组以在我的表中显示名称和 product__c? 目前我的通话显示名称和产品未定义

cols += '<td> ' + row.name + '</td>';
cols += '<td> ' + row.product__c + '</td>';

这里是 Ajax:

$.ajax({
                url: event.target.action,
                method: event.target.method,
                
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    console.log('#### sucessful data retrieve string' + JSON.stringify(data));

                     $.each(data.rows, function(row) {
                        console.log('#### ROWS ' + row);

                        var newRow = $("<tr>");
                            var cols = "";
                           
                            var contractName = $("#name").val();
                            var productName = $("#product__c").val();
                            cols += '<td> ' + row.name + '</td>';
                            cols += '<td> ' + row.product__c + '</td>';
                            newRow.append(cols);
                            $("#panel tbody").append(newRow);
                     });

                    $("#messageContract").text("Success!");
                    $("#messageC").show();
                },
                error: function(err) {
                    errorMessage.text(err.responseJSON.error);
                    error.show();
                }
            })

【问题讨论】:

    标签: jquery arrays json ajax loops


    【解决方案1】:

    请更正$.each循环,$.each中回调函数的第一个参数是索引,第二个是每个迭代项。

    $.each(data.rows, function(index,row) {
                            console.log('#### ROWS ' + row);
    
                            var newRow = $("<tr>");
                                var cols = "";
                               
                                var contractName = $("#name").val();
                                var productName = $("#product__c").val();
                                cols += '<td> ' + row.name + '</td>';
                                cols += '<td> ' + row.product__c + '</td>';
                                newRow.append(cols);
                                $("#panel tbody").append(newRow);
                         });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 2016-05-01
      • 2020-12-17
      • 2021-11-15
      相关资源
      最近更新 更多