将表单数据转换为JSON对象

时间:2012-10-19 02:13:36

标签: jquery html json forms

我正在尝试将HTML表单数据转换为JSON对象,我有this thread,但我不知道为什么它不适合我。我使用以下代码。

<form id="myform" action="" method="post">
    <div class="form-field">
        <label for="title">Title</label>
        <input name="title" id="title" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field form-required">
        <label for="your-name">Your Name</label>
        <input name="yourName" id="yourName" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="contact-no">Contact No:</label>
        <input name="contact" id="contact" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="description">Description:</label>
        <textarea name="description" id="description" rows="1" cols="40" aria-required="true"></textarea>
    </div>
    <div class="form-field">
        <label for="email">Email:</label>
        <input name="email" id="email" type="text" value="optional" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="city">City:</label>
        <input name="city" id="city" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="country">Country:</label>
        <input name="country" id="country" type="text" value="" size="40" aria-required="true">
    </div>
    <div class="form-field">
        <label for="pic1">Picture 1:</label>
        <input type="file" name="pic1" id="pic1">
    </div>
    <div class="form-field">
        <label for="pic2">Picture 2:</label>
        <input type="file" name="pic2" id="pic2">
    </div>
    <div class="form-field">
        <label for="pic3">Picture 3:</label>
        <input type="file" name="pic3" id="pic3">
    </div>
    <div class="form-field">
        <label for="pic4">Picture 4:</label>
        <input type="file" name="pic4" id="pic4">
    </div>
    <div class="form-field">
        <label for="pic5">Picture 5:</label>
        <input type="file" name="pic5" id="pic5">
    </div>
    <div class="form-field">
        <label for="demand">Your Demand:</label>
        <input name="demand" id="demand" type="text" value="" size="40" aria-required="true">
    </div>
    <p class="submit">
        <input type="submit" name="postAd" id="postAd" class="button" value="Post Ad For Review">
    </p>
    <div id="results">hello</div>
</form>

$(document).ready(function(){
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.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 {
                alert(this.name);
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $('#myform').submit(function() {
        $('#result').text(JSON.stringify($('#myform').serializeObject()));
        return false;
    });
});

我尝试调试它,我注意到当我的函数运行时,它总是在else语句中运行代码。

6 个答案:

答案 0 :(得分:16)

我在JSFiddle中添加了上面的表单,它将JSON数据显示为输出。

Working JSFiddle

$(function() {
  $('form').submit(function() {
     $('#result').text(JSON.stringify($('form').serializeObject()));
    return false;
  });
});

答案 1 :(得分:3)

使用此jQuery插件 .serializeJSON()将表单数据转换为JSON对象。

<form id="my-profile">
<!-- simple attribute -->
    <input type="text" name="fullName" value="Mario Izquierdo" />

<!-- nested attributes -->
    <input type="text" name="address[city]" value="San Francisco" />
    <input type="text" name="address[state][name]" value="California" />
    <input type="text" name="address[state][abbr]" value="CA" />
</form>

使用Javascript:

$('#my-profile').serializeJSON();

// returns =>
{
    fullName: "Mario Izquierdo",

    address: {
    city: "San Francisco",
    state: {
    name: "California",
    abbr: "CA"
    }
}

serializeJSON()函数返回一个JSON对象。

答案 2 :(得分:2)

使用Jsbin示例http://jsbin.com/oTimiGE/1/edit

尝试jquery serializeArray()方法

http://api.jquery.com/serializeArray/

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});

答案 3 :(得分:1)

对于谷歌搜索者,

我已经创建了像这样的序列化形式的JSON数组,

   var jsonArray = [];

   var splittedFormData = $("#formToPost").serialize().split('&');

            $.each(splittedFormData, function (key, value) {

                item = {};
                var splittedValue = value.split('=');               
                item["name"] = splittedValue[0];
                item["value"] = splittedValue[1];
                jsonArray.push(item);
            });

   console.log(jsonArray)

答案 4 :(得分:0)

也许只使用jquery序列化函数?

$("#myform").serialize()

一旦拥有JSON对象,您可以稍后进行其他处理。

答案 5 :(得分:-1)

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.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;
};

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});