如何在JSON中使用switch case

时间:2016-09-22 08:06:30

标签: javascript asp.net json

我正在尝试使用JSON开关案例显示正常消息。我已经编写了代码,代码也在下面

<script type="text/javascript">
    var text = '{ "R000092201": "EIN and Name should be same","F229000501":"Your Form is Incomplete, Please add the Credit Vehicle Details (Contact Support for any further queries)","F229002201":"Your Form is Rejected, Please ensure you select either EFW or EFTPS Payment (Contact Support for any further queries)"}';

    var obj = JSON.parse(text);
    var clients = '<%= clients%>';
    alert(clients);
    switch (clients) {
        case 'R0000-922-01': document.getElementById('lblrejectionmsg').innerHTML = obj.R000092201;

        case 'F2290-005-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229000501;

        case 'F2290-022-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229002201;
    }
</script>

在基于后端数据的上述代码中,即&lt;%= clients%&gt; 应执行相应的案例,但在我的代码中,它不是例如客户端值无关始终显示第3个案例消息。在我出错的地方,请帮助我。

1 个答案:

答案 0 :(得分:0)

每个案例后你都错过了break;

<script type="text/javascript">
    var text = '{ "R000092201": "EIN and Name should be same","F229000501":"Your Form is Incomplete, Please add the Credit Vehicle Details (Contact Support for any further queries)","F229002201":"Your Form is Rejected, Please ensure you select either EFW or EFTPS Payment (Contact Support for any further queries)"}';

var obj = JSON.parse(text);
var clients = '<%= clients%>';
alert(clients);
switch (clients) {
    case 'R0000-922-01': document.getElementById('lblrejectionmsg').innerHTML = obj.R000092201;
    break;
    case 'F2290-005-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229000501;
    break;
    case 'F2290-022-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229002201;
    break;
}

如果你错过了休息时间;总是匹配案例后的所有情况都会执行。所以添加休息;在每个案件块之后。