如何使用jQuery循环访问JSON数组

时间:2015-05-14 00:43:34

标签: javascript jquery arrays json

我正在尝试遍历JSON数组。

这是示例输出

{
    "calls": [
        [
            {
                "interactionId": "2002766591",
                "account_id": "",
                "mid": "",
                "Eic_CallDirection": "O",
                "Eic_RemoteAddress": "5462223378",
                "Eic_LocalAddress": "1062",
                "Eic_State": "I"
            }
        ]
    ],
    "status": [
        {
            "statusId": "Available",
            "userId": "su",
            "loggedIn": false
        }
    ]
}

这是我的jQuery代码。

<script>
$(function(){

    function isset(a, b){

        if(typeof a !== "undefined" && a){
            return a
        }

        return b;
    }

    setInterval(function() {

        $.getJSON("showMEssages.php", {method: "getMessages"}, function(data){

            if(data.calls.length == 0 || !data.calls){
                console.log('No Messages');
            }
            var c;

            $.each(data.calls, function(i, item){

                c = item[i];
                console.log(c);

                var interactionId = isset(c.interactionId, 0);
                var Eic_CallDirection = isset(c.Eic_CallDirection, '');
                var Eic_State = isset(c.Eic_State, '');
                var AccoRDI_mid = isset(c.AccoRDI_mid, '');
                var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');

                if( Eic_CallDirection == 'I' && Eic_State == 'A'){
                    console.log('Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
                }

                if(Eic_CallDirection == 'O' && Eic_State == 'C'){
                    console.log('Live Call With ' + Eic_RemoteAddress );
                }


            });
        });

    }, 1000);
});
</script>

我的代码正在运行,但是因为它每秒运行一次我在日志中不断收到此错误

TypeError: c is undefined

并且错误指向此行

console.log(c);

这个问题的原因是什么?我该如何纠正?

2 个答案:

答案 0 :(得分:2)

在此功能中:

$.each(data.calls, function(i, item){});

itemdata.calls中每个元素的值,因此您无需使用item[i]。只需c = item即可。

答案 1 :(得分:0)

我想出了这个问题。因为我在数组中有数组

,所以我必须在循环中进行循环
        $.each(data.calls, function(i, item){

            $.each(item, function(z, c){

                var interactionId = isset(c.interactionId, 0);
                var Eic_CallDirection = isset(c.Eic_CallDirection, '');
                var Eic_State = isset(c.Eic_State, '');
                var AccoRDI_mid = isset(c.AccoRDI_mid, '');
                var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');

                if( Eic_CallDirection == 'I' && Eic_State == 'A'){
                    console.log('Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
                }

                if(Eic_CallDirection == 'O' && Eic_State == 'C'){
                    console.log('Live Call With ' + Eic_RemoteAddress );
                }

            });
        });