提交数据并在不刷新页面的情况下显示


Submit data and display without page refresh

我有一个使用基本MVC结构的小网站。我有一些代码可以在数据库中插入两个值,插入操作很好,没有任何问题,但是,如果我想查看新数据,我通常必须刷新页面或导航到另一个页面,然后返回。我知道我需要使用JQuery/Ajax来实现这一点,但我并不真正理解如何使用PHP函数。

有问题的代码如下:

PHP函数:

<?php
session_start();
require_once('../Config/config.php');
class Readings 
{
    public $dbconn;
    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->dbconn = $db;
    }
    public function enterElecReadings($eUsage)
    {
        try
        {       
            $estmt = $this->dbconn->prepare("
                INSERT INTO elec_readings
                    (ElecUsage, DateAdded, AccountNumber) 
                VALUES
                    (:eUsage, NOW(), :accNum)");
            $estmt->bindparam(":eUsage", $eUsage);
            $estmt->bindparam(":accNum", $_SESSION['user_session']);
            $estmt->execute();  
            return $estmt;
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }   
    }
    public function getElecReadings(){
        try {
            $stmt = $this->dbconn->prepare("SELECT ElecUsage, DateAdded FROM elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "'");
            $stmt->execute();
            return $stmt;
        } catch (Exception $e) {
        }
    }
}
?>

用户将看到的页面:

    if(isset($_POST['btn-submitElecUsage']))
    {
        $eUsage = strip_tags($_POST['txtElecUsage']);
        try {
            if($newReading->enterElecReadings($eUsage)){    
                $elecNotif[] = "Reading successfully entered.";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
<div class="elecUsage">
        <form id="elecRead" method="POST">
            <h2>Electricity Usage</h2>
            <?php
            if(isset($elecError))
            {
                foreach($elecError as $elecError)
                {
                    ?>
                    <div class="alert alert-danger">
                        <?php echo $elecError; ?>
                    </div>
                    <?php
                }
            }
            if(isset($elecNotif))
            {
                foreach($elecNotif as $elecNotif)
                {
                    ?>
                    <div class="alert alert-danger">
                        <?php echo $elecNotif; ?>
                    </div>
                    <?php
                }
            }
            ?>
            Please enter your latest electricity meter reading:
            <br>
            <input type="text" name="txtElecUsage" required/>
            <br>
            <input type="submit" name="btn-submitElecUsage" value="Submit"/>
        </form>

        <br>
        Your previous Electricity meter readings:
        <br>
        <div id="previousElecReadings">
            <br>
            <table class="tableElec" >
                <thead>
                    <tr>
                        <th>Usage</th>
                        <th>Date Added</th>     
                    </tr>
                </thead>
                <?php
                foreach ($elec_readings as $elec_reading): ?>
                <tbody>
                    <tr>
                        <td><?php echo $elec_reading['ElecUsage']; ?></td>
                        <td><?php echo $elec_reading['DateAdded']; ?></td>
                    </tr>
                    <?php
                    endforeach;
                    ?>
                </tbody>
            </table>
        </div>
    </div>

控制器类别:

<?php
require_once('../Model/readingsModel.php');
require_once('../Tool/DrawTool.php'); 
$newReading = new Readings();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/meterReadings.php', array('elec_readings' => $newReading->getElecReadings()), 
    array('gas_readings' => $newReading->getGasReadings()));
echo $renderedView;
?>

正如我上面所说的。插入效果良好。但我希望看到数据立即出现,而不是必须刷新。

有什么想法吗?

感谢

它真正做的一切就像一个浏览器,在后台点击该页面。你可以选择是否回叫数据,但就好像你的浏览器已经转到了那个页面,所以你把它当作其他页面一样对待。这只是一个破解的剪切和粘贴,但这可能很接近:

index.php(不管您的初始页面叫什么):

    <!-- use the id to target the form -->
    <form id="elecRead" method="POST">
        <h2>Electricity Usage</h2>
        <!-- You just have an empty container where your ajax will return -->
        <div id="errors"></div>
        Please enter your latest electricity meter reading:
        <br>
        <input type="text" name="txtElecUsage" required/>
        <br>
        <input type="submit" name="btn-submitElecUsage" value="Submit"/>
    </form>
    ...etc...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script>
    // When page is done loading
    $(document).ready(function(){
        // When this particular form is submitted
        $('#elecRead').submit(function(e){
            // Stop normal refresh of page
            e.preventDefault();
            // Use ajax
            $.ajax({
                // Send via post
                type: 'post',
                // This is your page that will process the update 
                // and return the errors/success messages
                url: "page2.php",
                // This is what compiles the form data
                data: $(this).serialize(),
                // This is what the ajax will do if successfully executed
                success: function(response){
                    // It will write the html from page2.php into an 
                    // element with the id of "errors", in our case
                    // it's a div
                    $('#errors').html(response);
                },
                //  If the ajax is a failure, this will pop up in the console.
                error: function(response){
                    console.log(response);
                }
            });
        });
    });
    </script>

page2.php(处理页面):

<?php
// Page two just contains the processing of the update
// so include everything that you need to do that
session_start();
require_once(__DIR__.'/../Config/config.php');
require_once(__DIR__.'/../Model/readingsModel.php');
// Check for the post
if(isset($_POST['btn-submitElecUsage'])){
        // Create the instance of your class that does the update and error
        // handling/rendering
        $newReading = new Readings();
        $eUsage = strip_tags($_POST['txtElecUsage']);
        try {
            if($newReading->enterElecReadings($eUsage)){    
                $elecNotif[] = "Reading successfully entered.";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
// I am just using a buffer, but you don't need it
ob_start();
    // I presume this variable is on an included page, I don't see it 
    // anywhere but if you include the same stuff as your initial page,
    // it should show up here fine
    if(isset($elecError)){
        foreach($elecError as $elecError){
            ?>
            <div class="alert alert-danger">
                <?php echo $elecError; ?>
            </div>
            <?php
        }
    }
    if(isset($elecNotif)){
        foreach($elecNotif as $elecNotif){
            ?>
            <div class="alert alert-danger">
                <?php echo $elecNotif; ?>
            </div>
            <?php
        }
    }
$data = ob_get_contents();
ob_end_clean();
// Just print the contents of the page and your ajax on page 1
// will take this content and place it in the <div id="errors"><div>
die($data);

使用纯php,如果不刷新页面,就无法做到这一点。所以使用AJAX!

这里有一个的小例子

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    </head>
    <body>
        <input type="text" id="name"/>
        <input type="submit" id="submit" value="Send"><br/><br/>
        <div id="response"><div>
        <script>
        $(document).ready(function(){
            $('#submit').click(function(e){
                e.preventDefault();
                var value = $('#name').val();
                if (value != ''){
                    $.ajax({
                        type: "POST",
                        url: "your_process_file.php",
                        data: { name:value },
                        success: function(data){
                            $('#response').html(data);
                        },
                        fail: function(data){
                            $('#response').html('There is an error!');
                        }
                    });
                }
            });
        });
        </script>
    </body>
</html>

您的_process_file.php可能看起来像:

$name = $_POST['name'];
$stmt = $db->prepare('SELECT * FROM tblName WHERE name=?');
$stmt->execute([$name]);
while ($row = $stmt->fetch()){
    echo $row['col1'],' ',$row['col2'],' ',$row['colN'];
}

假设数据库表中有一些数据:

id名称地址

1 abc地址1

2 def address2

然后,当您在文本框fe,abc中写入时,表中的整行将返回到<div id="response"></div>中,而不刷新页面。

OBS:我认为代码中可能有一些错误,因为我没有测试它。