簡體   English   中英

提交數據並顯示,無需頁面刷新

[英]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>

而 your_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'];
}

並假設您在 db 表中有一些數據:

身份證姓名地址

1個ABC地址1

2 定義地址2

然后,當您在文本框中寫入 fe, abc 時,表格中的整行將在<div id="response"></div>而不會刷新頁面。

OBS:我認為代碼中可能存在一些錯誤,因為我沒有對其進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM