我有以下格式的json响应:
[
{
"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."
}
]
到目前为止,我在以下代码中使用jQuery ajax访问它:
$(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对象,为了简单而不是检查整个代码,我在这里删除了var行:
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的正确方法还是有正确的&amp;更简单的方法?
提前致谢。
答案 0 :(得分:1)
因为我肯定会花一些时间改进那个javascript对象结构,如果这是你可以控制的。
例如,为什么问题在"2"
内的数组中? "0"
和"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代码将更容易阅读。
您总是使用data[0]
,但我认为JSON响应的第一级是数组的原因是因为响应中可能还有其他问题/对象。
如果确实如此,那么您可能希望始终使用$.each
中的每个子对象而不是data[0]
:
$.each(function(index, obj) {
var theQ = obj[2][0]['question']; //notice "obj" instead of "data[0]"
...
}
创建变量并使用中间步骤中的变量,同时深入了解JSON结构。这将有助于您提高代码可读性。
例如:
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