我正在创建一个移动应用程序,它依赖 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 中完成的?我进行了广泛的搜索,一切似乎都不适合我想做的事情。谢谢。
最佳答案
参见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();
关于jquery - 是否有更有效的方法将表单元素映射到表单提交中的 jSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700488/