2014-03-05 24 views
0

创建我写这篇文章的代码:变化JSON形式从

$(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; 
}); 
+0

谢谢它的工作原理,但我发现一个问题,我有这个有输入[类型=“复选框”]:检查......但对于输入[类型=“文本“]:检查它不工作,为什么和解决方案是什么? – user3357400

+0

@ user3357400:无法检查文本输入。你想做什么? –