我写这段代码:
$(function() {
$('form').submit(function() {
var voter = [];
var voted_questions = [];
var answers = [];
$('input[type="radio"]:checked').each(function(){
voted_questions.push($(this).data('questionid'));
answers.push({'question':$(this).data('questionid'),'options':this.value});
});
$('input[type="checkbox"]:checked').each(function(){
voted_questions.push($(this).data('questionid'));
answers.push({'question':$(this).data('questionid'),'options':this.value});
});
$('input[type="text"]').each(function(){
voted_questions.push($(this).data('questionid'));
answers.push({'question':$(this).data('questionid'),'custom':this.value});
});
$('input[type="hidden"]').each(function(){
if ($(this).data('voter') == 'ip_address')
voter.push({'ip_address':this.value});
if ($(this).data('voter') == 'voting_started')
voter.push({'voting_started':this.value});
if ($(this).data('voter') == 'voting_ended')
voter.push({'voting_ended':this.value});
});
var data = {
'voter': voter,
'voted_questions': voted_questions,
'answers': answers
};
$('#result').text(JSON.stringify(data));
return false;
});
});
演示:http://www.jsfiddle.net/B9r22/5
我不知道如何从[]
删除voter
。我想让json像这样:
'voter':
{
'ip_address': a.b.c.d,
'voting_started':voting_started,
'voting_ended': voting_ended,
}
答案 0 :(得分:0)
您正在将voter
作为数组([]
),然后将对象推入其中。要获得所需内容,请将voter
设为对象({}
)并添加所需的键/值对。
var voter = {};
$('input[type="hidden"]').each(function(){
if ($(this).data('voter') == 'ip_address')
voter.ip_address = this.value;
if ($(this).data('voter') == 'voting_started')
voter.voting_started = this.value;
if ($(this).data('voter') == 'voting_ended')
voter.voting_ended = this.value;
});