donglanfu5831 2019-02-01 18:07
浏览 116
已采纳

我的JSON数组如何被格式化以迭代这个$ .each?

I need to iterate through data that get via JSON with this code:

setInterval(function() {

        console.log("running");
        $.ajax({
            type     : 'get',
            url      : 'data.txt',
            dataType : 'json',
            success  : function(response) {

                console.log(response.bookings) // returns undefined

                $.each(response.bookings, function(index, booking) {
                    sc.status(booking.seat_id, 'unavailable');

                    console.log(booking.seat_id); // returns nothing

                });
            }
        });
    }, 3000); //every 3 seconds

The data is currently formatted like this:

[{
  "bookings": [
    {
      "seat_id": "1_4"
    },
    {
      "seat_id": "4_2"
    }]
}]

But that doesn't seem to be working. What is the correct format that I need to use? I tried a ton of options but can't get it working.

UPDATE:

The error I now get in the console is:

jquery-1.11.0.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined
    at Function.each (jquery-1.11.0.min.js:2)
    at Object.success ((index):145)
    at j (jquery-1.11.0.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
    at x (jquery-1.11.0.min.js:4)
    at XMLHttpRequest.b (jquery-1.11.0.min.js:4)

and line 145 is:

$.each(response.bookings, function(index, booking) {

  • 写回答

3条回答 默认 最新

  • doucheyi1347 2019-02-03 10:25
    关注

    I finally found the solution. Thank you to everyone who helped. It's pretty simple and stupid. I only had to change the JSON response from:

    [{
      "bookings": [
        {
          "seat_id": "1_4"
        },
        {
          "seat_id": "4_2"
        }]
    }]
    

    to

    {
      "bookings": [
        {
          "seat_id": "1_4"
        },
        {
          "seat_id": "4_2"
        }]
    }
    

    Basically get rid of the []

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环