将表单数据存储到json

时间:2017-08-29 12:45:13

标签: javascript html json reactjs

我为注册表单编写了此代码。我想以数组对象的形式将电子邮件ID和密码的值添加到JSON文件中。

这是我的html文件。

<!DOCTYPE html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta name="robots" content="noindex, nofollow" charset="UTF-8">

</head>

<body>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
  <script type="text/javascript" src="jQuery-UI.js"></script>
  <script src="validate.js"></script>

  <form id="myform" enctype="application/json">
    <div class="container-form">
      <fieldset>
          <legend>Sign up</legend>

          <label for="username">User Name</label><br>
          <input type="text" name="username[]" id="username" placeholder="Your name" minlength="2" required=""><br><br>

          <label for="contact">Contact</label><br>
          <input name="contact" type="number" id="contact" placeholder="Phone Number" >
          <br><br>
          <label for="emailid">Email id</label><br>
          <input type="email" name="emailid[]" id="email" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" placeholder="Enter email id" required=""><br><br>

          <label for="password">Password</label><br>
          <input type="password" name="password[]" id="password" placeholder="Enter password" required="" minlength="6"><br><br>

          <label for="password">Confirm Password</label><br>
          <input type="password" name="cpassword" id="cpassword" placeholder="Confirm Password"><br><br>

          <button type="submit" name="register" id="register" value="Submit">Submit</button>
          <button type="reset" value="Clear">Clear</button>
          <div id="result">
          </div>
      </fieldset>
    </div>
  </form>
</body>

我的submit.js已被转换为bundle.j,因为require()不能直接使用。 这是我的submit.js

    (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

var fs = require('fs');

$(function() {
    $(document).ready(function(){
        $("#myform").validate({
            rules: {
                password: "required",
                cpassword: {
                    required: true,
                    equalTo: "#password"
                }
            },

            messages: {

                cpassword: {
                    required: 'Please re-enter the password',
                    equalTo: 'Please enter the same password'
                }
            }
        });

        $("#register").on('click', function(){

      var data1 = fs.readFileSync('data.json');
      var words = JSON.parse(data1);

      function make_json(form){
            var jsonObject = {
            "name" : $("#username").val(),
            "email" : $("#email").val(),
                    "password": $("#password").val()
            };
            console.log(jsonObject);
      };
      var data2 = JSON.stringify(jsonObject, null, 2);
      fs.writeFile("./data.json", data2, finished);

      function finished(err) {
        console.log('all set.');
      }
        });
    });
});


},{"fs":2}],2:[function(require,module,exports){

},{}]},{},[1]);

我哪里错了?如果可能,发送编辑的代码而不是链接到某个网站。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以从输入中获取值,我看到您正在使用jQuery,所以这里是您的用户名输入字段的示例

var userName = $('#username').val(); //the # tells jQuery you are specifying an elements id, use a . (dot) tho specify a class

你可以在json中这样做 首先定义一个json对象

var containerName = {};

将您的值添加到容器

containerName.userName = $('#username').val();

您可以使用

将对象转换为字符串
var string = JSON.stringify(containerName);

这些是从某种结构中获取表单值的一些基本操作。希望这会有所帮助。

答案 1 :(得分:1)

当您标记了您的问题Php时,我将给您一个提交表单的粗略要点,进行一些服务器端验证。如果满足验证,则将以JSON格式提交的数据存储在文件中。

此处不包含Javascript。

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = [
        'name' => null,
        'password' => null,
        'cpassword' => null,
        'email' => null
    ];

    foreach($data as $k => $v) {
        if(!empty($_POST[$k]))
            $data[$k] = $_POST[$k];
    }

    $validated = true;
    if($data['password'] !== $data['cpassword'])
        $validated = false;

    if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL))
        $validated = false;

    if($validated) {
        if(file_put_contents('/tmp' . '/' . uniqid('json_'), json_encode($data, JSON_PRETTY_PRINT)))
            $feedback = 'Thanks.  Submission stored.';
    }
    else {
        $error = 'Please fill in all your form fields correctly.';
    }

}

?>
<?= isset($error)    ? $error    : '' ?>
<?= isset($feedback) ? $feedback : '' ?>

<form method="post">
    <label for="name">Name</label>
    <input type="name" name="name" id="name" placeholder="e.g. John Doe" required>

    <label for="email">Email address</label>
    <input type="email" name="email" id="email" placeholder="e.g. john.doe@example.com" required>

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="e.g. S3cR3t" required>

    <label for="password">Confirm Password</label>
    <input type="password" name="cpassword" id="cpassword" placeholder="e.g. S3cR3t" required>
    <input type="submit" value="Go">
</form>

当然,它可以通过一些可用性增强功能来实现 - 例如告诉用户他们究竟出了什么问题。但是你明白了。