簡體   English   中英

如何將表單作為JSON對象提交

[英]how to submit form as JSON object

我正在做的是使用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這樣做:

<?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');
    }
    });
});

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM