访问JSON对象最好还是正确的方法是什么? [英] Best or Correct way for accessing json object?

查看:199
本文介绍了访问JSON对象最好还是正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式提交JSON响应:

I have json response within following format:

[
  {
    "0": [
        {
            "tVote": "32"
        }
    ],
    "1": [
        {
            "choice": "Barcelona",
            "tbAns": "2"
        },
        {
            "choice": "Bayern Muenchen",
            "tbAns": "2"
        },
        {
            "choice": "Juventus",
            "tbAns": "20"
        },
        {
            "choice": "Manchester United",
            "tbAns": "5"
        },
        {
            "choice": "Real Madrid",
            "tbAns": "3"
        }
    ],
    "2": [
        {
            "question": "Favorite football team ?"
        }
    ],
    "status": "positive",
    "msg": "Thank you, your vote has been count."
  }
]

到目前为止,我accesing内使用下面的code jQuery的阿贾克斯的:

So far, i accesing it using jQuery ajax within following code:

$(function() {
    $('.vote').click( function(e) {
        e.preventDefault();
        var parId = $(this).closest('form').attr('id');
        var itemId = $(this).prev('input[name=q_id]').val();
        var formAction = $('#' + parId).attr('action');

        $.ajax({
            type      : 'POST',
            url       : formAction,
            data      : $('#' + parId + '').serializeArray(),
            dataType  : 'json',
            beforeSend: function() {
                $('.loadPoll-' + itemId).removeClass('hidden');
            },
            error     : function(request, status, error) {
                $('#' + parId).html('sorry can\'t send your request, please try again later<br>' + status + ' ' + error);
            },
            success   : function(data) {
                $('.loadPoll-' + itemId).addClass('hidden');
                $.each(data, function() {
                    var theQ = data[0][2][0]['question'];
                    var msg = data[0]['msg'];
                    var status = data[0]['status'];
                    var totalVoter = data[0][0][0]['tVote'];
                    var item = data[0][1];
                    var itemLength = data[0][1].length;
                    var itemChoice = data[0][1][0].choice;
                    var parental = $('.vote:focus').closest('form').attr('id');

                    //create html template for response
                    var template = '<div class="clearfix panelPoll">';

                    if(status === 'negative') {
                        $.amaran({
                            content        : {
                                bgcolor: '#FF9900',
                                message: msg,
                                color  : '#fff',
                                icon   : 'fa fa-download'
                            },
                            theme          : 'colorful',
                            position       : 'bottom right',
                            cssanimationIn : 'swing',
                            cssanimationOut: 'bounceOut'
                        });

                        template += '<div class="row bg-info"><p>' + theQ + '</p><code>Total voter: <span class="badge">' + totalVoter + '</code></span></div>';
                        template += '<div class="clearfix"></div>';
                        template += '<div class="row resultPollBody">';
                        for(var j = 0; j < itemLength; j++) {
                            //console.log(data[0][1][j].choice); // (debug only)return loop of answer
                            //console.log(data[0][1][j]['tbAns']) // (debug only)return loop of total voter per answer
                            var percent = Math.round((data[0][1][j]['tbAns'] / totalVoter) * 100);
                            (function(j) {

                                template += '<p class="text-primary">' + data[0][1][j].choice + ' <span class="badge">' + data[0][1][j]['tbAns'] + '</span></p>';
                                template += '<div class="progress">';
                                template += '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="' + percent + '" aria-valuemin="0" aria-valuemax="100" style="width:' + percent + '%;">' + percent + '%</div>';
                                template += '</div>';
                            })(j)
                        }
                    }
                    else if(status === 'positive') {
                        //code here for new vote
                        $.amaran({
                            content        : {
                                bgcolor: '#008000',
                                message: msg,
                                color  : '#fff',
                                icon   : 'fa fa-download'
                            },
                            theme          : 'colorful',
                            position       : 'bottom right',
                            cssanimationIn : 'swing',
                            cssanimationOut: 'bounceOut'
                        });

                        template += '<div class="row bg-info"><p>' + theQ + '</p><code>Total voter: <span class="badge">' + totalVoter + '</code></span></div>';
                        template += '<div class="clearfix"></div>';
                        template += '<div class="row resultPollBody">';
                        for(var j = 0; j < itemLength; j++) {
                            //console.log(data[0][1][j].choice); // (debug only)return loop of answer
                            //console.log(data[0][1][j]['tbAns']) // (debug only)return loop of total voter per answer
                            var percent = Math.round((data[0][1][j]['tbAns'] / totalVoter) * 100);
                            (function(j) {

                                template += '<p class="text-primary">' + data[0][1][j].choice + ' <span class="badge">' + data[0][1][j]['tbAns'] + '</span></p>';
                                template += '<div class="progress">';
                                template += '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="' + percent + '" aria-valuemin="0" aria-valuemax="100" style="width:' + percent + '%;">' + percent + '%</div>';
                                template += '</div>';
                            })(j)
                        }
                    }

                    //closing tag for template
                    template += '</div></div>';

                    $('#' + parental).html(function() {
                        $(this).html(template);
                    });
                })
            }
        })
    });
});

所以,我宣布变量访问JSON对象,为简便起见,而不是检查整个$ C $词切无功行这里:

So, i declaring variable to access the JSON object, for simplicity rather than checking the whole code i cut the var line here:

var theQ = data[0][2][0]['question'];
var msg = data[0]['msg'];
var status = data[0]['status'];
var totalVoter = data[0][0][0]['tVote'];
var item = data[0][1];
var itemLength = data[0][1].length;
var itemChoice = data[0][1][0].choice;
var parental = $('.vote:focus').closest('form').attr('id');  

它的工作并没有什么错,我得到了我想要的结果,但我想知道像我在标题所说,这是正确的方式访问JSON或有正确的&放大器;更简单的方法?

Its worked and nothing wrong, i got the result i want but i want to know like i stated within title, is this correct way for accessing the JSON or there is correct & simpler way?

在此先感谢。

推荐答案

由于我会确定花一些时间来提高Javascript对象结构,如果这是你的控制之下。

Is the JSON response part of YOUR code?

Because I would definetly spend some time improving that javascript object structure if that is under your control.

例如,为什么有一个数组里面的问题在2?与同为01

For instance, why have the question inside an array inside a "2"? And the same for "0" and "1".

为什么不只是有:

[
    {
        "question": "Favorite football team ?",
        "tVote": "32",
        "choices": [
            {
                "choice": "Barcelona",
                "tbAns": "2"
            },
            ...
        ],
        "status": "positive",
        "msg": "Thank you, your vote has been count."
    },
    {
        "question": "Another question ?",
        ...
    }
]

如果你做这些改变你的访问,这将是一个很多更容易阅读的JavaScript code。

If you do these changes your javascript code that access this will be a lot more easier to read.

您始终使用数据[0] ,但我想,之所以JSON响应的第一级是一个数组,因为可能还有其他的问题/对象在响应中。

You are always using data[0], but I suppose that the reason the first level of the JSON response is an array is because there might be other questions/objects in the response.

如果这是真的,那么你可能要使用的每个子对象的 $。每个而不是数据[0] 总是:

If that is true, then you probably want to use each sub-object in the $.each instead of data[0] always:

$.each(function(index, obj) {
    var theQ = obj[2][0]['question']; //notice "obj" instead of "data[0]"
    ...
}

使用变量而不是复制code

请变量,使用你在中间步骤,而在JSON结构不断深入的变量。这将帮助你提高code可读性。

Use variables instead of copying code

Make variables and use the variables you have in intermediate steps while going deeper in the JSON structure. This will help you improve code readability.

例如:

var item = obj[1]; // according to what I said about $.each
var itemLength = item.length; // instead of obj[1].length
var itemChoice = item[0].choice; // instead of obj[1][0].choice

这篇关于访问JSON对象最好还是正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆