JavaScript打印和AJAX保存/删除数据库

JavaScript print and AJAX save/delete from database

本文关键字:删除 数据库 保存 AJAX 打印 JavaScript      更新时间:2023-09-26

我已经创建了这个页面,从数据库中获取数据,链接打印显示的数据,然后删除它。

其中一个问题是JavaScript打印函数window.print();不能工作。

另一个问题是,打印完这一页后,我想更新数据库,这样人们就可以看到它之前已经打印过了。

或者,该函数也可以打印页面,然后立即删除数据,这样人们就不需要查看之前是否打印过。

这是从数据库中获取数据的代码:

<html>
<header>
<script>
function print_table(id)
{
   //print your document
   window.print();
   //send your data
   xmlhttp=new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
   xmlhttp.send();
}
</script>
</header>
<body>
<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
 while($rows = $resultSet->fetch_assoc())
 {
   $id = $rows['id'];
   $naam = $rows['naam'];   
   $achternaam = $rows['achternaam'];
   $email = $rows['email'];
   $telefoon = $rows['telefoon'];   
   $bestelling = $rows['bestelling'];   
   echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
 }
// Display the results 
}else{
   echo "Geen bestellingen";
}
?>
</body>
</html>

,这些是两个服务器端功能的页面:

delete.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
        // Get ID
        $id = $_GET['del'];
        $sql= "DELETE FROM orders WHERE id=" . $id . "";
        // Create connection
        $conn = mysqli_connect($servername, $username, $password, $dbname);
        // Query the database
        $resultSet = $conn->query($sql) or die("Failed".mysql_error());
        echo "<meta http-equiv='refresh' content='0;url=http://localhost/Stage%201/bestellingen.php'>";
?>

print_table.php

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1  WHERE `id` = `$id`");
?>

你应该检查你的浏览器控制台(F12),看看是否有任何JavaScript错误。

我能发现的一个非常明显的错误是这一行,括号没有关闭。这些类型的错误可以很容易地修复,只要先检查控制台。

另一个错误是字符串中的变量,它应该作为?key=value对发送。

xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
应:

xmlhttp.open("GET","http://localhost/Stage/printed_table.php?id=" + id, true);

另一个问题是上面那行调用的URL。我注意到你提到你的PHP文件名是print_table。PHP 而不是printed_table。PHP .