jquery - 是否有更有效的方法将表单元素映射到表单提交中的 jSON 字符串?

标签 jquery json

我正在创建一个移动应用程序,它依赖 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/

相关文章:

javascript - 如何使用 jquery 将 div 动画化为不同的方向并淡出

javascript - 使用 JavaScript 构建猜数游戏程序

java - .execute 无法解析为类型 - AsyncTask (Android)

java - 使用Java修改JSON

java - Play Framework JSON 表单的类型选择

jquery - 在运行时启用/禁用悬停样式?

jquery - jquery不移动背景图像

javascript - 具有任意区域(有进度)的饼图动画,无闪光灯

javascript - Status-415 Nodejs 中指定的内容类型无效错误

python - 使用 Python 解析 JSON - 如何访问深层元素