验证JSON数组长度

时间:2015-10-29 18:06:41

标签: javascript arrays json oracle-apex

我正在尝试编写一个if语句,用于确定getDept JSON数组是否包含多个值。如果是,则重定向到其他页面。通过我的研究,它看起来像getDept.length > 1一样简单,但我无法做到这一点。

我的Javascript代码如下:

$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept) 
{
    console.log(getDept);
    if(getDept.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.length > 1)
        {   
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});

getDept JSON数组包含以下信息:

{
    "next": {
        "$ref": "https://apex.oracle.com/pls/apex/mfajertest1/department/%7Bid%7D?page=1"
    },
    "items": [
        {
            "deptno": 10,
            "dname": "accounting",
            "loc": "madison"
        },
        {
            "deptno": 20,
            "dname": "Finance",
            "loc": "Milwaukee"
        },
        {
            "deptno": 30,
            "dname": "IT",
            "loc": "La Crosse"
        },
        {
            "deptno": 40,
            "dname": "Purchasing",
            "loc": "Green Bay"
        },
        {
            "deptno": 10,
            "dname": "Accounting II",
            "loc": "Madison II"
        },
        {
            "deptno": 50,
            "dname": "Sports",
            "loc": "Waukasha"
        }
    ]
}

如果需要,我很乐意提供有关此问题的更多信息。

1 个答案:

答案 0 :(得分:5)

您的JSON响应实际上是一个对象,而不是一个数组。您要检查的数组是该对象中名为items的属性。因此,无论您在何处使用getDept,都应使用getDept.items

$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept) 
{
    console.log(getDept.items);
    if(getDept.items.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.items.length > 1)
        {   
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});
相关问题