简体   繁体   English

有没有什么办法可以在不刷新页面的情况下做到这一点?

[英]Is There Any Way I Can Do This Without Refreshing The Page?

I am trying to create and edit button, like Reddit has, for my forum.我正在尝试为我的论坛创建和编辑按钮,就像 Reddit 一样。 I have got it to work but I was wondering if I'd be able to do it without having to refresh the page.我已经让它工作了,但我想知道我是否能够在不必刷新页面的情况下做到这一点。

For example, when I click the edit button, it reloads the page and displays the form for editing, then when I click save it will reload yet again to display the new edited post.例如,当我单击编辑按钮时,它会重新加载页面并显示用于编辑的表单,然后当我单击保存时,它将再次重新加载以显示新编辑的帖子。

Code (EDITED from IncredibleHat's answer):代码(从 IncredibleHat 的答案中编辑):

<?php

session_start();

$host = "host"; // Host name 
$user = "username"; // Mysql username 
$password = "password"; // Mysql password 
$db_name = "database"; // Database name 
$tbl_name = "fquestions"; // Table name 

// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect"); 
mysqli_select_db($conn, $db_name)or die("cannot select DB");

// get value of id that sent from address bar 
$id = $_GET['id'];
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_array($result);

/*Check if topic is locked or not */
$locked = $rows['locked'];

if ($_SESSION['username'] == $rows['username']) {
    $editPost = true;
}
?>

<head>

    <!-- ****** faviconit.com favicons ****** -->
    <link rel="shortcut icon" href="../images/favicon.ico">
    <!-- ****** faviconit.com favicons ****** -->

    <link id ="pageStyle" rel="stylesheet" href='../css/defaultStyle.css' type='text/css'> <!-- Loads Default Stylesheet -->
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto' type='text/css'>
    <script src='https://www.google.com/recaptcha/api.js'></script>

</head>

<body>     
    <div id="mainContent">
        <div id="question">
            <p id="date"><?php echo $rows['datetime']; ?></p>
            <h2><?php echo $rows['topic']; ?></h2>
            <b><p><?php echo $rows['username']; ?></p></b>
            <?php
            // The Regular Expression filter
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

            // The Text you want to filter for urls
            $text = htmlspecialchars($rows['detail']);

            // Check if there is a url in the text
            if(preg_match($reg_exUrl, $text, $url)) {
                $url = preg_replace("/^http:/i", "https:", $url);

                // make the urls hyper links
                echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a><br>', '<p id="post">'.$text.'</p>');

            } else {
                ?>
            <p id="post"><?php echo htmlspecialchars($rows['detail']); ?></p>
            <?php
            }

            if ($editPost == true) {
                $_SESSION['detail'] = $rows['detail'];
                $_SESSION['id'] = $rows['id'];
                ?>
                <style>
                    #editPostButton {
                        border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
                    }

                    #editPostButton.dark {
                        color: white;
                        background-color: #1C1C1C;
                    }
                </style>
                <input type="submit" value="Edit" name="editPostButton" id="editPostButton" data-postId="<?php echo $rows['id']; ?>">
                <div id="editFormBlock"></div>

                <script>
                   $(document).ready(function() {
                       // for clicking on the edit button, to grab the edit form
                       $("#editPostButton").on('click',function(e) {
                           e.preventDefault();
                           $.post(
                               'ajaxhandler.php',
                               { action: 'editform', postid: $(this).data('postId') },
                               function(htmlReturn) {
                                   $("#editFormBlock").html( htmlReturn ); // replace editForm content
                                },
                                'HTML'
                                );
                       });

                       // for clicking the save button for a edit form
                       // using .on so it catches dynamically added content
                       $("#editFormBlock").on('click',"#saveButton",function(e) {
                           e.preventDefault();
                           var data = $("#editForm").serializeArray();
                           data.push({name: 'action', value: 'saveform'});
                           $.post(
                               'ajaxhandler.php',
                               data,
                               function(htmlReturn) {
                                   $("#editFormBlock").html( '' ); // clear edit form out
                                },
                                'HTML'
                                );
                       });
                   });
                </script>
                <?php
            }
            ?>
        </div>

<?php

$tbl_name2="fanswer"; // Switch to table "forum_answer"
$sql2 = "SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2 = mysqli_query($conn, $sql2);
$row_cnt = mysqli_num_rows($result2);

if ($row_cnt > 0) {
    ?>
    <h3>Replies:</h3>
    <div id="replies">

    <?php
    while($rows = mysqli_fetch_array($result2)) {
    ?>
        <p id="dates"><?php echo $rows['a_datetime']; ?></p>
        <div id="reply">
        <b><p><?php echo $rows['a_username']; ?></p></b>
        <?php
        // The Regular Expression filter
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

        // The Text you want to filter for urls
        $text = htmlspecialchars($rows['a_answer']);

        // Check if there is a url in the text
        if(preg_match($reg_exUrl, $text, $url)) {
            $url = preg_replace("/^http:/i", "https:", $url);

            // make the urls hyper links
            echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);

        } else {
            ?>
            <p><?php echo htmlspecialchars($rows['a_answer']); ?></p>
            <?php
        }
        ?>
        </div>
        <?php
    }
} else {
    ?>
    <div id="answers">
        <p style="color: red;">There doesn't seem to be anything here</p>
    <?php
}

$sql3 = "SELECT view FROM $tbl_name WHERE id='$id'";
$result3 = mysqli_query($conn, $sql3);
$rows = mysqli_fetch_array($result3);
$view = $rows['view'];

// if have no counter value set counter = 1
if(empty($view)) {
    $view = 1;
    $sql4 = "INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'";
    $result4 = mysqli_query($conn, $sql4);
}

// count more value
$addview = $view+1;
$sql5 = "update $tbl_name set view='$addview' WHERE id='$id'";
$result5 = mysqli_query($conn, $sql5);
mysqli_close($conn);
?>
    </div>
    <h3>Post A Reply:</h3>
    <form name="form1" method="post" action="add-answer" autocomplete="off">
    <label>Reply: </label>
<?php
if ($locked == 1) {
    echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>🔒 This topic is locked! 🔒</textarea><br>';
} else if ($_SESSION['logged_in'] != true) {
    echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>⛔ You must login to reply! ⛔</textarea><br>';
} else {
    echo '<textarea name="a_answer" id="a_answer" maxlength="300" required style="width: 800px;"></textarea><br>
    <div class="g-recaptcha" data-sitekey="6LdrxD4UAAAAACAaVAR6U9BjOEDC9-j4QaOzBsFh"></div>
    <input type="submit" name="submit" value="Submit">
    <input type="reset" name="reset" value="Reset">';
}
?>
    <input name="id" type="hidden" value="<?php echo $id; ?>">
    </form>
    </div>
</body>

ajaxhandler.php: ajaxhandler.php:

<?php

session_start();

$detail = $_SESSION['detail'];
$id = $_SESSION['id'];

if (!empty($_POST['action'])) {
    if ($_POST['action'] == 'editform') {
        ?>

        <style>
            #post, #editPostButton {
                display: none;
            }

            #saveButton {
                border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
            }
        </style>

        <form id="editForm">
            <textarea name="detail"><?php echo $detail; ?></textarea><br>
            <input type="button" id="saveButton" value="Save">
        </form>
        <?php
    }
    if ($_POST['action'] == 'saveform') {
        // do save process to db
        // echo out a new static post html block

        $host = "host"; // Host name 
        $user = "username"; // Mysql username 
        $password = "password"; // Mysql password 
        $db_name = "database"; // Database name 
        $tbl_name = "fquestions"; // Table name 

        // Connect to server and select databse.
        $conn = mysqli_connect($host, $user, $password)or die("cannot connect"); 
        mysqli_select_db($conn, $db_name)or die("cannot select DB");

        $sql = "UPDATE $tbl_name SET detail = '$detail' WHERE id=$id";
        $result = mysqli_query($conn, $sql);
    }
}
?>

Two ways you could do the toggling of an edit form.您可以通过两种方式切换编辑表单。

  1. Load in more html (sub parts, not whole html documents) with ajax calls, and replace existing elements with the new html chunks based on actions.使用 ajax 调用加载更多 html(子部分,而不是整个 html 文档),并根据操作用新的 html 块替换现有元素。 Click the edit button, it calls ajax to 'get the form block', and then it replaces some slot on the page with it.单击编辑按钮,它调用 ajax 来“获取表单块”,然后用它替换页面上的某个插槽。 Submitting the form, tosses that form, and replaces it with the new static text block.提交表单,丢弃该表单,并用新的静态文本块替换它。 This is generally a cleaner way to handle it.这通常是一种更简洁的处理方式。

  2. Have all the relevant bits in the html DOM on first load of the php script.在第一次加载 php 脚本时在 html DOM 中包含所有相关位。 Have many parts hidden .隐藏了很多部分。 Then clicking certain buttons, or doing actions shows/hides elements based on those actions.然后单击某些按钮,或执行操作根据这些操作显示/隐藏元素。 This is easier, but not as clean, as all your form submit elements and actions, as well as the original static parts, are all in the HTML on every general page load.这更容易,但不是那么干净,因为所有表单提交元素和操作,以及原始静态部分,都在每个常规页面加载的 HTML 中。

An example of loading in a edit form on edit-button click, and swapping content blocks:单击编辑按钮时加载编辑表单并交换内容块的示例:

Basic static HTML framework (from first load of main.php):基本的静态 HTML 框架(从 main.php 的第一次加载开始):

<p id="post">[the original post html here]</p>

<?php if ($editPost == true) { /* dont bother if they have no edit rights */?>
<input type="button" id="editPostButton" value="Edit" data-postId="<?php echo $postId;?>">
<div id="editFormBlock"></div>
<?php }?>

Script area (jquery required):脚本区(需要jquery):

<script language="Javascript" type="text/javascript">
$(document).ready(function() {

    // for clicking on the edit button, to grab the edit form
    $("#editPostButton").on('click',function(e){
        e.preventDefault();
        $.post(
            'ajaxhandler.php',
            { action: 'editform', postid: $(this).data('postId') },
            function(htmlReturn){
                $("#editFormBlock").html( htmlReturn ); // replace editForm content
            },
            'HTML'
        );
    });

    // for clicking the save button for a edit form
    // using .on so it catches dynamically added content
    $("#editFormBlock").on('click',"#saveButton",function(e){
        e.preventDefault();
        var data = $("#editForm").serializeArray();
            data.push({name: 'action', value: 'saveform'});
        $.post(
            'ajaxhandler.php',
            data,
            function(htmlReturn){
                $("#post").html( htmlReturn ); // replace static post content
                $("#editFormBlock").html( '' ); // clear edit form out
            },
            'HTML'
        );
    });

});
</script>

The ajaxhandler.php : ajaxhandler.php

// Have blocks that pertain to the $_POST['action']
if (!empty($_POST['action'])) {
    if ($_POST['action'] == 'editform') {

        // do a database select on using the postId
        // grab the data you wish to use in the edit form

        // build a form and echo it out for the ajax return
        echo '
        <form id="editForm">
            <input type="hidden" name="postId" value="'. $row['id'] .'">
            <textarea name="detail">'. $row['detail'] .'</textarea>
            <input type="button" id="saveButton" value="Save">
        </form>
        ';
    }
    if ($_POST['action'] == 'saveform') {

        // put your "save to database" code here
        // that uses $_POST['postId'], $_POST['detail'] etc

        // after saving, grab a fresh copy of the post
        // and then echo out a new static html #post content
        echo htmlspecialchars($row['detail']);
    }
}

I hope this was clear enough to understand to get a foothold on what you wish to do.我希望这足够清楚,以了解您希望做的事情。 There is a lot more you can do, with an extra errorBlock to show errors, and handling of results.您可以做更多事情,使用额外的errorBlock来显示错误和处理结果。 You can even push in some animations too.你甚至可以推送一些动画。 Endless possibilities.无限可能。

NOTE: I should warn you though, that this is all based off your example, where you are showing just one post, and one edit form.注意:我应该警告你,这都是基于你的例子,你只展示了一篇文章和一个编辑表单。 This uses "ID"s, which must be unique on the page.这使用“ID”,它在页面上必须是唯一的。 If you are planning on pouring many posts on ONE page, you will need to adjust everything to use classes and enumerated ID's to keep the unique.如果您打算在一个页面上发布许多帖子,则需要调整所有内容以使用类和枚举 ID 以保持唯一性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 提交后如何重设电子邮件表单,以便可以发送另一封电子邮件而无需刷新页面 - How do I reset an email form after submission so that another email can be sent without refreshing the page 如何自动刷新多个PHP变量而不刷新页面? 我只能做一个自动取款机 - how to auto refresh multiple php variables without refreshing page? I can only do one atm 我如何不刷新即可更改页面的内容 - how i can i change the content of a page without refreshing 如何在不刷新页面的情况下显示错误? - How do I show an error without refreshing the page? 如何在不刷新当前页面的情况下在另一个页面上发布? - How do I post on another page without the current one refreshing? 如何在不刷新页面的情况下自动提交此表单? - How do I automatically submit this form without refreshing the page? 如何提交表单而不刷新当前页面? - How do I submit a form without refreshing the current page? 如何在不刷新页面的情况下不断更新PHP变量? - How can I continuously update a PHP variable without refreshing a page? 我如何在不刷新页面的情况下计算php中的视频观看次数 - How can i count video view in php without refreshing page 如何在不刷新页面的情况下刷新MySQL查询的结果? - How can I refresh the results of a MySQL query without refreshing the page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM