PHP實現沒有數據庫提交form表單到後臺而且顯示出數據列表(Vuejs和Element-UI前端設計表單)

1.情境:若是你新建了個網站,卻沒有數據庫服務器,如何把你的表單信息,提交到服務端後臺,收集數據。php

2.思路:若是用傳統的form action 提交到一個form.php頁面,此時只能存儲一次數據,再次提交會覆蓋以前的數據。html

第一種方法:此時考慮新建一個文件能夠存放數據。txt文件能夠存儲數據,json文件也能夠存儲數據,此案例採用把收集到的數據爲數組格式,直接存入php文件中,並在另外一個文件中讀取存入的數組。vue

異步提交form表單數據,使用$ajaxajax

表單樣式和數據呈現表單:數據庫

 

 

1.使用Vuejs和Element-UI組件設計表單驗證json

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="NAME & SURNAME*" prop="name">
                    <el-input v-model="ruleForm.name" name="username"></el-input>
                  </el-form-item>
      <el-form-item
        prop="email"
        label="EMAIL*"
      >
        <el-input v-model="ruleForm.email" name="email"></el-input>
      </el-form-item>
    <el-form-item
        prop="phone"
        label="PHONE"
      >
        <el-input v-model="ruleForm.phone" name="phone"></el-input>
      </el-form-item>
      <el-form-item label="POSITION*" prop="position">
        <el-select v-model="ruleForm.position" name="position">
          <el-option  v-for="item in options" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <input name="submitdate" type="hidden" id="inittime" value=""/>
      <el-form-item>
        <el-button type="primary" @click="register">提交</el-button>
      </el-form-item>
    </el-form>
//此時表單驗證的一些設定
<script>
// 建立根實例,使用vuejs和Element-UI
new Vue({
  el: '#app',
  data() {
      return {
          options: [{
        value: 'CustomerRepresentative',
        label: 'Customer Representative'
      }, {
        value: 'RetentionRepresentative',
        label: 'Retention Representative'
      }, {
        value: 'HumanResources',
        label: 'HumanResources'
      }],
      default: 'CustomerRepresentative',
           ruleForm: {
          name: '',
          email: '',
          phone:'',
          position:'CustomerRepresentative',
              },
        rules: {
          name: [
            { required: true, message: 'Please enter your name and surname *', trigger: 'blur' },
          ],
          email:[
            { required: true, message: 'Please enter your email *', trigger: 'blur' },
            { type: 'email', message: 'Please enter your correct email *', trigger: ['blur', 'change'] }
            ],
            phone:[
            { required: true, message: 'Please enter your phone *', trigger: 'blur' },
            ]
            },
            position: [
            { required: true, message: '請選擇活動區域', trigger: 'change' }
          ],
        }
    },
</script>
建立form表單

2。收集表單數據,並使用formData,使用Jquery的ajax提交數據給新的文件數組

<script>
            methods: {
            register: function () {
                /**date**/
                var date = new Date();
                var seperator1 = "-";
                // var seperator2 = ":";
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
            //時間格式爲YY-MM-DD HH:mm:ss
                var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    // + " " + date.getHours() + seperator2 + date.getMinutes()
                    // + seperator2 + date.getSeconds();
                    $('#inittime').val(currentdate);

             let data=this.ruleForm;
             let formData=new FormData();
             formData.append('name',data.name);
             formData.append('email',data.email);
             formData.append('phone',data.phone);
             formData.append('position',data.position);
             formData.append('submitdate',currentdate);
             // console.log(formData.get('submitdate'));
         $.ajax({
              url:"form.php",
              type:'post',
              cache:false,
              processData: false,
            contentType: false,
               data:formData,

       success: function(msg){
        alert('Thanks,Your information has submitted');
       // console.log(msg);
       //  $("#result").append("你的名字是:"+msg.name+"");
    }
    });


        }
  },
</script>
定義FormData數據,ajax提交表單

!!!:此時的dataType能夠省略不寫,會自動讀取所提交的數據格式。服務器

3.定義提交的form.php文件,並把收集到的數組保存到新的php文件中(此時個人文件:menugroup.php)app

<?php
header("Content-type:text/html;charset=utf-8");
    $username = $_POST['name']; //獲取索引
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $position = $_POST['position'];
    $submitdate = $_POST['submitdate'];
    $dd = array('username'=>$username,'email'=>$email ,'phone'=>$phone,'position'=>$position,'date'=>$submitdate); //轉換成數組類型
            $cachefile ='menugroup.php';
            echo (var_export($dd,true));
            //exit();
            $arr = include('menugroup.php');
            $arr[] =$dd;
            $str = "<?php return ".var_export($arr,true).';';
            echo $str;
            file_put_contents($cachefile,$str);
            //alert("保存成功!");
        
?>
提交數據的form.php文件

4.messages.php讀取數組爲table表單在頁面中。異步

<?php
// 從文件中讀取數據到PHP變量
header("Content-type:text/html;charset=utf-8");
$json_string = include('menugroup.php');
// $json_string=stripslashes(html_entity_decode($json_string));


// 把JSON字符串轉成PHP數組
// $data =json_decode($json_string, true );
 
// 顯示出來看看
// var_dump($json_string);
// echo $data['name'];
echo '<table border="1" width="700" align="center" cellpadding="0" cellspacing="0">';
    echo '<caption><h1>Application Information</h1></caption>';
    echo '<tr bgcolor="#dddddd">';
    echo '<th>ID</th><th>NAME</th><th>EMAIL</th><th>PHONE</th><th>POSITION</th><th>DATE</th>';
    echo '</tr>';
    foreach($json_string as $k => $v){
          // echo $k . '<br>';
   //       print_r($v);
   //       echo '<br>';
      echo '<tr><td>'.($k+1).'</td>';
         foreach ($json_string[$k] as $index => $value) {
          // echo $k . '<br>';
            // echo $index . '<br>';
            echo '<td align="center">'.$value.'</td>';
         }
         echo '</tr>';
}
    echo '</table>';
?>
讀取數據到頁面中

 下面是嘗試使用純JavaScript實現ajax異步提交數據

var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function()
                {
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    {
                        var formresult = xmlHttp.responseText;
                        alert('sussess');
                        // console.log(formresult);
                    }
                }
                 xmlHttp.open("post", "form.php",true); 
                 xmlHttp.send(formData);
相關文章
相關標籤/搜索