如何在html中使用javascript自动更新数据库mysql

8fsztsew  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(421)

我想在倒计时为==0或<0时自动更新数据库,而不重新加载页面。只有特定的块将被重新加载或重新加载脚本/代码。当距离<0时,如何在mysql中自动更新数据库?我尝试重新加载();and.load(location.href(“#”);但他们会重新加载页面。
我使用php作为我的后端
在javascript中

<script type="text/javascript">     
    function createCountDown(elementId, date) {

    var countDownDate = new Date(date).getTime();

    var x = setInterval(function() {

      var now = new Date().getTime();

      var distance = countDownDate - now;

      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      document.getElementById(elementId).innerHTML = days + 'd ' +
                                                     hours + 'h ' +
                                                     minutes + 'm ' + 
                                                     seconds + 's ';

      if (distance < 0) {
        clearInterval(x);
        document.getElementById(elementId).innerHTML = "Expired";
      }
    }, 1000);
}
hujrc8aj

hujrc8aj1#

你需要使用ajax。
例子:

xhttp.open("POST", "path/to/post/handler.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

就你而言:

if (distance < 0) {
    clearInterval(x);
    document.getElementById(elementId).innerHTML = "Expired";
    //this is where you update the database:
    xhttp.open("POST", "path/to/post/handler.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //use the xhttp object to send(POST) values to the database.
    xhttp.send("message=Expired&id=242");

}

更多信息请点击此处
你在后台用什么?您需要处理javascript post:
例如:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$stmt = $this->mysqli->prepare("UPDATE yourTable SET status=? WHERE id=?");
$stmt->bind_param('si', $_POST['message'], $_POST['id']);
$stmt->execute();
return $stmt->affected_rows;
$conn->close();
?>

让我在评论中知道它是否有效。。。

相关问题