我正在创建一个依赖jSON将表单提交到数据库的移动应用程序。我有我的提交功能:
function sendJson(service, method, json) {
var request = $.ajax ({
type: 'POST',
url: '/remoteserver/service/' + service + '/' + method,
dataType: 'json',
async: false,
data: JSON.stringify(json),
success: function (msg) {
alert('Success ' + JSON.stringify(msg.location));
},
error: function(msg) {
alert('YOU SUCK' + JSON.stringify(msg));
}
});
}
目前正在使用类似的东西来填充jSON字符串:
$("element").click(function(){
var wrapper = {};
var location = {};
wrapper.location = location;
location.name = $('#name').val();
location.address1 = $('#address1').val();
location.address2 = $('#address2').val();
location.city = $('#city').val();
location.state = $('#state').val();
location.country = $('#country').val();
location.zipCode = $('#zipCode').val();
location.contactName = $('#contactName').val();
location.contactPhone = $('#contactPhone').val();
sendJson("locationService", "createLocation", wrapper);
});
我的问题是这个 - 我将在这个应用程序中有近100个表单。我如何将每个jSON元素(? - IE location.name)映射到表单字段,而不必显式地声明location.name = $('#name).val();
,或者这是如何在jSON中完成的?我进行了广泛的搜索,一切似乎都不适合我想做的事情。谢谢。
答案 0 :(得分:2)
请参阅Convert form data to JavaScript object with jQuery:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
现在你可以像这样序列化它:
$('#YourFormID').serialzeObject();
答案 1 :(得分:1)
您可以使用.serialize()
将一组表单元素编码为字符串以供提交。
所以你可以这样做:
var data = $('#YourFormID').serialize();