【问题标题】:Get data JsonArray and JsonObject via $.each Jquery通过 $.each Jquery 获取数据 JsonArray 和 JsonObject
【发布时间】:2018-08-15 15:00:03
【问题描述】:

我有这个,从 laravel API 创建的数据 json

[
    [{
        "id": 4,
        "name": "Customer-izlgy",
        "email": "ycgjl@xxyin.com"
    }, {
        "id": 5,
        "name": "Customer-bkxjn",
        "email": "wlrew@iloiv.com"
    }],
    [{
        "id": 1,
        "name": "Customer-izlgyt",
        "email": "ycgjl@xxysdin.com"
    }, {
        "id": 2,
        "name": "Customer-bkxjnyf",
        "email": "wlrew@iloifsv.com"
    }]
]

我试图通过 ajax 获取数据 id 4 和 id 1,但总是出错 Uncaught TypeError: Cannot read property 'name' of undefined

这是我从上述数据 json 中获取名称的代码。

// get customer data that has been handled
function callHandledCustomer() {
  $.ajax({
    type: "GET",
    url: rootUrl + "/api/chat/getHandledCustomer",
    dataType: "json",
    success: function(response){
      $.each(response, function(i, customer) {
        console.log(customer[0][0].name); // get name
      });
    }

  });
}

非常感谢

【问题讨论】:

    标签: jquery arrays json ajax


    【解决方案1】:

    您只需删除与您的对象布局不匹配的第二个[0]。

    var response = [
        [{
            "id": 4,
            "name": "Customer-izlgy",
            "email": "ycgjl@xxyin.com"
        }, {
            "id": 5,
            "name": "Customer-bkxjn",
            "email": "wlrew@iloiv.com"
        }],
        [{
            "id": 1,
            "name": "Customer-izlgyt",
            "email": "ycgjl@xxysdin.com"
        }, {
            "id": 2,
            "name": "Customer-bkxjnyf",
            "email": "wlrew@iloifsv.com"
        }]
    ];
    
    $.each(response, function(index, customer){
      console.log(customer[0].name);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多