【问题标题】:Is there a way to fetch record from db without reloading a page有没有办法在不重新加载页面的情况下从数据库中获取记录
【发布时间】:2022-11-29 13:36:48
【问题描述】:

如何在不刷新页面的情况下单击按钮从我的数据库中获取我的数据,即电影名称?我正在构建一个宾果游戏,我试图在其中放置一个历史记录按钮以在下拉菜单的上下文中显示我的数据请参考我下面的代码和帮助!

--这是我的 history.php 文件

            <?php

            require_once 'config.php';
            ?>
            <!DOCTYPE html>
            <html>
            <style>
                #rec_mode{
                    background-image: url('register.png');
                    background-size: 100% 100%;
                    width: 100px;
                    height: 50px;
                    border: none;
                    outline: 0px;
                    -webkit-appearance: none;  
                }
            </style>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script>
            history_num_arr = [];
                // For showing latest image from host -- end 
                $(function () {
                    var latestNum;
                    history_num_arr = [];
                    var url = "fetch_num.php";
                    setInterval(function () {
                    tempArr = [];
                    $("#number").load(url);
                    imgNum = jQuery("#number").text();
                    // $("#PostIMG").attr("src", "movie poster/" + imgNum + ".jpg");

                    if (history_num_arr[history_num_arr.length - 1] != imgNum) {
                        history_num_arr.push(imgNum);
                        if (localStorage.getItem("history_num") === null) {
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                    }
                    else if ((history_num_arr.length === 1) && (localStorage.getItem("history_num") != null)) {
                            console.log("hello");
                            tempArr = JSON.parse((localStorage.getItem("history_num")));
                            history_num_arr = JSON.parse(JSON.stringify(tempArr));
                            console.log(history_num_arr);
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                    }
                    else if ((history_num_arr.length > 1) && (localStorage.getItem("history_num") != null)) {
                            console.log(history_num_arr);
                            localStorage.setItem("history_num", JSON.stringify(history_num_arr));
                        }
                    }
                }, 1000);
            });


                // For showing latest image from host -- end 
                $(document).ready(function () {
                    $("#historybtn").click(function () {
                        var url = "history.php";
                        $("#history").load(url);
                        alert(history_num_arr.join(' '));
                    });
                });
            </script>
            <script>
            var myobject = {
                // history : '$history_num_arr'
                };
            var select = document.getElementById("rec_mode");
            for(index in myobject) {
                select.options[select.options.length] = new Option(myobject[index], index);
            }

            </script>
            <body>
                
            <div id="histarr"></div>
            <div id="fetch">
                <p style="display: none;">
                <p style="display: none;" id="number"></p>
                </p>
            </div>
            <div id="history_num">
                <p style="display: none;">
                <p style="display: none;" id="history"></p>
                </p>
            </div>
                <!-- <button id="historybtn" onclick = "">History</button> -->
                <!-- <select name = "select_history" id="dropdown"> --> 
            <select name = "select_history" id="rec_mode">
            <option selected="true" disabled="disabled">
            <?php

            require_once 'config.php';

            // $hist = mysqli_query($mysqli, "SELECT name FROM `movie_names` ORDER BY movieID DESC");
            $hist = mysqli_query($mysqli,"SELECT m.name FROM movie_names m INNER JOIN host_table ht WHERE m.movieID = ht.random_num ORDER BY ID DESC");
            while ($row = $hist->fetch_assoc())
            {
                echo "<option value=\"select_history\">".$row['name']."</option>";
                // exit(0);
            }
            ?>
            </option>
            </select>
                <!-- </select> -->



            </body>
            </html>

-- 这是我的 fetch_num.php 文件

            <?php 
            require_once 'config.php';
            // $sql = "SELECT  random_num FROM host_table ORDER BY ID DESC LIMIT 1;";
            $sql = "SELECT m.name FROM movie_names m INNER JOIN host_table ht WHERE m.movieID = ht.random_num ORDER BY ID DESC;";
            if($result = mysqli_query($mysqli,$sql)){
                if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_array($result)){ 
                        echo $row["name"];

                    }
                }
            }
            else{
                echo "Error".mysqli_error($mysqli);
            }
            ?>

--这是我的config.php文件

            <?php

                //Connecting to Database
                $host ="localhost";
                $user = "root";
                $pass ="";
                $db = 'randomized';

                //Creating a connection object
                $mysqli = mysqli_connect($host, $user, $pass, $db);
                echo "<br>";

                if (!$mysqli){
                die("Sorry we failed to connect: ". mysqli_connect_error());
                }
                else{
                    // echo "Connection done!";
                }

            ?>

【问题讨论】:

  • 一种解决方案是使用浏览器的 indexedDB

标签: javascript php jquery arrays ajax


【解决方案1】:

如果您不想重新加载页面,可以使用 javascript 来完成,我们有 setinterval 函数每隔一段时间获取一次 setInterval(() =&gt; { fetchData().then(data =&gt; updateTable(data)) }, 1000);

或通过按钮:

<button class="button-fetch" type="button" onclick="fetchData();">Fetch Data</button>

【讨论】:

    【解决方案2】:

    通过 PHP 加载数据后,您将无法动态加载数据,因为 PHP 仅在您加载页面时在服务器上运行。

    您必须使用 fetch API 来使用 JavaScript 发出请求。

    例如:

    async function loadRecords() {
      const records = await fetch('/records.php');
      return records;
    }
    

    有关 JavaScript fetch api 的信息,请参阅 MDN 文档。 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    【讨论】:

      【解决方案3】:

      如果您想在不重新加载网页的情况下从服务器获取数据,可以使用一个非常流行的工具。它被称为 AJAX(异步 Javascript XML)。 您可以创建一个单独的 PHP 文件来处理请求,然后您可以通过 AJAX 请求从那里获取数据。因为您使用的是 JQuery,所以它可能看起来像这样:

      $.ajax({url: /* your php file path */, type="POST", data: {data: /* request information */})
          .done(function(response){
              /* do some DOM manipultion with the response here */
          }
          .fail(function(response){
              console.log(response);
              /* standard function for catching errors */
          }         
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        • 2012-02-05
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        相关资源
        最近更新 更多