[英]How to loop through a JSON array using jQuery
我正在嘗試遍歷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);
此問題的原因是什么,如何解決?
在此功能中:
$.each(data.calls, function(i, item){});
item
是data.calls
中每個元素的值,因此您不需要使用item[i]
。 只需c = item
就足夠了。
我發現了問題。 我必須在一個循環中執行一個循環,因為我在其中使用了數組
$.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 );
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.