将表单数据存储到json [英] Storing form data to json

查看:217
本文介绍了将表单数据存储到json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我的html文件。

 <!DOCTYPE html> 

< head>
< link rel =stylesheettype =text / csshref =style.css>
< meta name =robotscontent =noindex,nofollowcharset =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 / javascriptsrc =jQuery-UI.js>< / script>
< script src =validate.js>< / script>

< form id =myformenctype =application / json>
< div class =container-form>
< fieldset>
<图例>注册< /图例>

< label for =username>使用者名称< / label>< br>
< input type =textname =username []id =usernameplaceholder =Your nameminlength =2required =>< br>< br>

< label for =contact>联络人< / label>< br>
< input name =contacttype =numberid =contactplaceholder =Phone Number>
< br>< br>
< label for =emailid>电子邮件ID< / label>< br>
< input type =emailname =emailid []id =emailpattern =[^ @] + @ [^ @] + \。[a-zA-Z] {2 ,6}placeholder =输入电子邮件地址required =>< br>< br>

< label for =password>密码< / label>< br>
< input type =passwordname =password []id =passwordplaceholder =Enter passwordrequired =minlength =6>< br>< br>

< label for =password>确认密码< / label>< br>
< input type =passwordname =cpasswordid =cpasswordplaceholder =Confirm Password>< br>< br>

< button type =submitname =registerid =registervalue =Submit> Submit< / button>
< button type =resetvalue =清除>清除< /按钮>
< div id =result>
< / div>
< / fieldset>
< / div>
< / form>
< / body>

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

 (function e(t,n,r){function s(o,如果(!u&& a)返回一个(o){if(!n [o]){if(!t [o]){var a = typeof require ==function&& require; ,!0); if(i)return i(o,!0); var f = new Error(Can not 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({ b $ b规则:{
password:required,
cpassword:{
required:true,
equalTo:#password
}
},

消息:{

cpassword:{
required:'请重新输入密码',
equalTo:'请输入相同的密码'
}
}
});

$(#register)。on('click',function(){

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

函数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);

函数完成(err){
console.log('all set。');
}
});
});
});

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

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

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

解决方案

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



不包含Javascript。



< pre $ <?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;
$ b $ if($ validated){
if(file_put_contents('/ tmp'。'/'。uniqid('json_'),json_encode($ data,JSON_PRETTY_PRINT)))
$ feedback ='谢谢。提交存储。';
}
else {
$ error ='请正确填写所有表单域。';
}

}

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

< form method =post>
< label for =name>名称< / label>
< input type =namename =nameid =nameplaceholder =例如John Doerequired>

< label for =email>电子邮件地址< / label>
< input type =emailname =emailid =emailplaceholder =例如john.doe@example.comrequired>

< label for =password>密码< / label>
< input type =passwordname =passwordid =passwordplaceholder =例如S3cR3trequired>

< label for =password>确认密码< / label>
< input type =passwordname =cpasswordid =cpasswordplaceholder =例如。S3cR3trequired>
< input type =submitvalue =Go>
< / form>

当然,这可以通过一些可用性增强来完成 - 比如告诉用户他们错在哪里。但你明白了。


I wrote this code for a sign up form. I want to add the values of email id and password to JSON file in the form of array objects.

Here is my html file.

<!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>

my submit.js which has been converted into bundle.j since require() cannot be used directly. here is my 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]);

Where am I going wrong? If possible send the edited code instead of link to some website. Thanks.

解决方案

As you've tagged your question Php, I'll give you a rough gist of submitting a form, doing some server side validation. And if the validation is satisfied store the data submitted in JSON format in a file.

No Javascript included here.

<?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>

Of course it could do with some usability enhancements - such as telling the user where exactly they went wrong. But you get the idea.

这篇关于将表单数据存储到json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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