简体   繁体   English

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

[英]how to submit form as JSON object

what I am doing is creating a form using JSON this form can then be edited a and produce new JSON object. 我正在做的是使用JSON创建一个表单,然后可以编辑该表单并生成新的JSON对象。 The problem I am having seems to be with getting the form id. 我遇到的问题似乎是获取表单ID。 The code I am using to return a JSON object is: 我用来返回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. 谢谢。

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? 如果您没有使用Ajax发送它,为什么要这样做呢? If you are simply submitting the form, you can do it using PHP like this: 如果您只是提交表单,可以使用PHP这样做:

<?php
$json_object = json_decode($_POST);
?>
$('#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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM