问题:我不知道如何根据API的需要完成格式化表单数据。
问题:我正在寻求你的帮助:)
HTML:
<form id="donation">
<fieldset>
<ul>
<li>
<input type="hidden" name="method" value="submitDonations" />
<input type="hidden" name="donor" value="Fred" />
<input type="hidden" name="donor_city" value="Nashville" />
<input type="hidden" name="donor_state" value="TN" />
<select name="donate_country">
<option value="choose_one">Choose One</option>
<option value="africa">Africa</option>
<option value="usa">USA</option>
<option value="china">China</option>
</select>
</li>
<li>
<label for="apples">Apples: </label>
<input type="number" name="apples" />
<label for="bananas">Bananas: </label>
<input type="number" name="bananas" />
<label for="pears">Pears: </label>
<input type="number" name="pears" />
</li>
<li>
<button>Donate</button>
</li>
</ul>
</fieldset>
</form>
使用Javascript / jQuery的
$('#donation').delegate('select', 'change', function(event) {
var self = $(event.target),
insertHere = $(self).parents('fieldset');
$('#donation')
.find('fieldset')
.first()
.clone()
.insertAfter($(insertHere));
});
$('#donation').delegate('button', 'click', function(e) {
e.preventDefault();
$('#donation').find('fieldset').each(function() {
//serializeArray() or something to go here but i can't figure it out
});
});
我需要提交的最终数组看起来像这样/是这种格式: method = submitDonations&amp; donor = Fred&amp; donor_city = Nashville&amp; donor_state = TN&amp; donations = [{donate_country:africa,apples:500,bananas:300,pears:200},{donate_country:use,apples:300,bananas:150,梨:400},{donate_country:中国,苹果:400,香蕉:320,梨:450}]
答案 0 :(得分:0)
谢天谢地......终于......我明白了。希望这会帮助其他人:
$('#donation').delegate('button', 'click', function(e) {
e.preventDefault();
var FORMDATA = {
method: $('#donation').find('input[name=method]').val(),
donor: $('#donation').find('input[name=donor]').val(),
donor_city: $('#donation').find('input[name=donor_city]').val(),
donor_state: $('#donation').find('input[name=donor_state]').val()
};
FORMDATA.donations = [];
var fieldsets = $('#donation').find('fieldset');
for(var f = 0; f < fieldsets.length - 1; f++) {
var fieldset = $(fieldsets[f]);
var inputs = fieldset.find(':input');
var data = {};
for(var i = 0; i < inputs.length; i++) {
data[$(inputs[i]).attr('name')] = $(inputs[i]).val();
}
FORMDATA.donations.push(data);
}
$.get('url/', JSON.stringify(FORMDATA), function(data, textStatus, jqXHR) {
if (//Errors) {
//handle errors
}
//do stuff with returnObject
});