如何将表单作为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; }); }); 

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

谢谢。

你的代码写得非常简单。 我是这样做的:

阿贾克斯:

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

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

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

如果你不想重定向或刷新使用e.preventDefault();