Javascript 如何将表单作为 JSON 对象提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11099069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to submit form as JSON object
提问by Sagarmichael
what I am doing is creating a form using JSON this form can then be edited a and produce new JSON object. The problem I am having seems to be with getting the form id. The code I am using to return a JSON object is:
我正在做的是使用 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;
});
});
This just refresh's the pageI am not sure why. This program is not on a server and not be used on a server. by this I mean It is only every going to be run locally on a local machine, with no apache2 setup.
这只是刷新页面我不知道为什么。该程序不在服务器上,也不能在服务器上使用。我的意思是它只是在本地机器上本地运行,没有 apache2 设置。
Thanks.
谢谢。
回答by OptimusCrime
You code can be written pretty easy. This is how I do it:
你可以很容易地编写代码。这就是我的做法:
Ajax:
阿贾克斯:
$('#formID').on('submit',function () {
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
If you are not sending it with Ajax, why would you do this? If you are simply submitting the form, you can do it using PHP like this:
如果您不使用 Ajax 发送它,为什么要这样做?如果您只是提交表单,则可以使用 PHP 来完成,如下所示:
<?php
$json_object = json_decode($_POST);
?>
回答by Osman Erdo?an
$('#formID').on('submit',function (e) {
e.preventDefault();
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
if you want not redirect or refresh use e.preventDefault();
如果你不想重定向或刷新使用 e.preventDefault();