PHP OOP AJAX表单提交数组不会附加

时间:2018-11-09 14:36:41

标签: php arrays ajax forms oop

我正在尝试将表单的POST数据显示在与Ajax相同的页面上。一切正常,但是我是OOP的新手,而我的使用POST内容构建数组的类在每次请求时都会被覆盖。

我知道我可以将数据发布到JSON文件或数据库中,但我希望它仅显示“增长中的”数组。

Index.php

<html>
<head>
    <head>
        <link rel="stylesheet" type="text/css" href="assets/css/style.css">
        <link href="https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,800" rel="stylesheet">
    </head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
        $(document).ready(function () {
            var frm = $('form');
            frm.submit(function (ev) {
                $.ajax({
                    type: frm.attr('method'),
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    success: function (data) {
                        $("#response").html(data);
                    }
                });
                ev.preventDefault();
            });
        });
    </script>
</head>
<body>
    <div class="wrapper">
        <div class="flex40">
            <div class="container40">
                <form id="form" action="response.php" method="post">
                    <input name="postName" type="text" placeholder="Name" required>
                    <select name="postEyeColour">
                        <option>Blue</option>
                        <option>Red</option>
                        <option>Yellow</option>
                        <option>Green</option>
                    </select>
                    <button name="submit" type="submit">New Person</button>
                </form>
                <div class="character-table">
                    <table id="response"></table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

response.php

<?php     
require_once 'Classes/Person.php';

$character = new Person;

if (isset($_POST['postName'])) {
    $character->createNewPerson();
    $character->getPersonList();
}    
?>

Classes / Person.php

<?php     
class Person {    
    private $personList = array();  

    public function createNewPerson() {    
        // Build Array From Post Data
        $newPerson= array(
            "Name" => $_POST['postName'],
            "Eye Colour" => $_POST['postEyeColour']
        );    
        //Push New Person to data array
        $this->personList[] = $newPerson;
    }

    public function getPersonList() {
        print_r($this->personList);
    }      
}    
?>

会发生什么情况,即数据已发布到数组,但是每次添加更多数据时,都会使用新数据重置数组,而不添加新数据。

0 个答案:

没有答案