如何将表单作为JSON对象提交

Sag*_*ael 6 javascript jquery serialization json

我正在做的是使用JSON创建一个表单,然后可以编辑该表单并生成新的JSON对象.我遇到的问题似乎是获取表单ID.我用来返回JSON对象的代码是:

form = document.forms[0];
$.fn.serializeObject = function()
{
    alert("start serializeObject");
    var o = {};
    var a = this.seralizeArray();
    $.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;
    alert(o);
};

$(function() {
    alert("here");
    form.submit(function(){
        result.append(JSON.stringify(form.serializeObject()));
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

这只是刷新页面我不知道为什么.此程序不在服务器上,不能在服务器上使用.通过这个我的意思是只有每一个都将在本地机器上本地运行,没有apache2设置.

谢谢.

Opt*_*ime 10

你可以很容易地编写代码.我是这样做的:

阿贾克斯:

$('#formID').on('submit',function () {
    $.ajax({
        url: 'submit.php',
        cache: false,
        type: 'POST',
        data : $('#formID').serialize(),
        success: function(json) {
            alert('all done');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您不是使用Ajax发送它,为什么要这样做?如果您只是提交表单,可以使用PHP这样做:

<?php
$json_object = json_decode($_POST);
?>
Run Code Online (Sandbox Code Playgroud)