使用纯JavaScript将HTML表单序列化为JSON [英] Serialize HTML form to JSON with pure JavaScript

查看:115
本文介绍了使用纯JavaScript将HTML表单序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了将表单序列化为JSON的这种方法,并且效果很好.我的问题是:如何在不使用任何jQuery代码的情况下使用纯JavaScript实现此目标?很抱歉,这个问题很愚蠢,但是我仍在学习,所以如果有人可以帮助我,我将不胜感激.

I have seen this method of serializing a form to JSON and it's working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery code? I am sorry if the question is dumb, but I'm still learning so if anyone can help me, I'll be grateful.

(function ($) {
    $.fn.serializeFormJSON = function () {

        var objects = {};
        var anArray = this.serializeArray();
        $.each(anArray, function () {
            if (objects[this.name]) {
                if (!objects[this.name].push) {
                    objects[this.name] = [objects[this.name]];
                }
                objects[this.name].push(this.value || '');
            } else {
                objects[this.name] = this.value || '';
            }
        });
        return objects;
    };
})(jQuery);

$('form').submit(function (e) {
    e.preventDefault();
    var data = $(this).serializeFormJSON();
    console.log(data);

    /* Object
        email: "value"
        name: "value"
        password: "value"
     */
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
    <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" id="password" />
    </div>
    <p>
        <input type="submit" value="Send" />
    </p>
</form>

P.S. 同样在jQuery中,这是从用户输入中作为一个字符串发送多个JSON对象的正确方法,因为我正在寻找一种方法来做到这一点?

P.S. Also in jQuery is this the right way to send multiple JSON objects from user input as One String, because I am searching for a way to do that?

推荐答案

您可以使用

// get array of all fields and/or selects (except the button)
const getFields = () => Array.from(document.querySelectorAll("input, select"))
    .filter(field => field.type.toLowerCase() !== "button");

// get id, name or create random id from field properties
const getKey = field => field.name 
  || field.id 
  || `unknown-${Math.floor(1000 * Math.random()).toString(16)}`;

// get data, simple object
const getFormData = () => getFields()
    .reduce( (f2o, field) => ({...f2o, [getKey(field)]: field.value}), {} );

// log the result
const logResult = txt => document.querySelector("#result").textContent = txt;

// get data, array of field objects
const getMoreFormData = () => getFields()
  .reduce( (f2o, field) =>
    f2o.concat({
        id: field.id || "no id",
        name: field.name || "no name",
        idGenerated: getKey(field),
        type: field.type, 
        value: field.value }
      ),
    [] );

// handling for buttons
document.addEventListener("click", evt => {
  if (evt.target.nodeName.toLowerCase() === "button") {
    console.clear();
    logResult(/simple/.test(evt.target.textContent)
     ? JSON.stringify(getFormData(), null, " ")
     : JSON.stringify(getMoreFormData(), null, " ")
    );
  }
} );

<form action="#" method="post">
  <div>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" value="Pete"/>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="text" name="email" id="email" value="pete@here.com"/>
  </div>
  <div>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" />
  </div>
  <div>
    <label>Field without name or id</label>
    <input type="number" value="12345" />
  </div>
</form>

<p>
  <button>Data simple object</button> <button>Data fields array</button>
</p>

<pre id="result"></pre>

这篇关于使用纯JavaScript将HTML表单序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆