javascript - 如何在不刷新页面的情况下刷新MySQL查询结果?

标签 javascript php jquery mysql

我想定期(例如每 10-30 秒)刷新一次查询的结果。我不确定如何将我在网上阅读的代码实现为我自己的代码,因为很多时候场景都是不同的。

MySQL 查询与我的 jQuery 和其他所有内容位于同一页面上。

目前,我使用这段 PHP 代码检索 MySQL 表的值:

$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");


while($row = mysqli_fetch_array($result))
  {
    echo "<form name='auction' id='auction" . $row['ID'] . "'>
            <input type='hidden' name='id' value='" . $row['ID'] . "' />
            <div class='auction-thumb'>
                <div class='auction-name'>" . $row['Item'] . "</div>";
            echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
            echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
            echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
            echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
            echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
    echo "</div></form>";
  }
echo "</table>";

mysqli_close($con);

?>

这会检索多行并填充页面。

我想经常刷新或“重新运行”此查询,以便更新当前出价。

我已经有了这个 jQuery 代码,它将新的出价发布到 PHP 页面,目前,查看此页面的任何其他人都不会看到新的出价,直到他们手动刷新页面,这不太好。

    <script>
    $(document).ready(function(){
        $('form[name="auction"]').submit(function(){
            var id = $(this).find('input[name="id"]').val();
            var bidname = $(this).find('input[name="bidname"]').val();
            var bid = $(this).find('input[name="bid"]').val();
            var currentbid = $('#'+id).text();
            var itemdesc = $(this).find('.auction-name').text();

            if (bidname == '')
            {
                alert("No name!")
                return false;   
            }

            if (bid > currentbid)
            {
                alert("Bid is greater than current bid");   
            }
            else
            {
                alert("Bid is too low!");
                return false;   
            }

            $.ajax({
            type: "POST",
            url: "auction-handler.php",
            data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
            success: function(data){
                window.location.reload();
            }
        });
        return false;

        }); 
    });
</script>

我的auction-handler.php代码:

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

$con=mysqli_connect("xxxx","xxxx","xxxx","xxxx");

if (mysqli_connect_errno())
    {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];

$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";

$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";



mysqli_query($con, $query) or die(mysqli_error());

mysqli_query($con, $query2) or die(mysqli_error());

mysqli_close($con);
?>

我在网上读到的很多东西并没有真正帮助我,而且我是一个初学者,无法自己正确地编写它们。有些事情我真的很难理解如何做,以及如何在我的场景中实现它。

非常感谢任何建议。

最佳答案

你离我们并不遥远。

您需要做的是用ajax请求的响应替换相关表的html,而不是重新加载整个页面。

所以代替:

success: function(data){
            window.location.reload();
        }

你可以这样做:

success: function(data){
            $('#auction'+id).before(data).remove();
        }

编辑

定期ajax请求:

php:

//update-handler.php
$response = array();

$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");


 while($row = mysqli_fetch_array($result)){
  $response[] = (object)array('id'=>$row['ID'],'val'=>$row['CurrentBid']);
 // get all the updated rows and put them into response array;
 }

header('content-type=application/json');
exit(json_encode($response)); // send the json serialized response to jquery ajax

JavaScript:

var timeout = 30000 //30 seconds
setInterval(function () {

    $.ajax({
    type: "POST",
    url: "update-handler.php",
    success: function (data) {
        $(data).each(function (i, d) {  //loop though each bid amount from ajax response
            $('#auction' + d.id).find('.nospace').html(d.val); //nospace is not a good target name, but its the only unique selector for that div

        });
    }
    });
}, timeout);

关于javascript - 如何在不刷新页面的情况下刷新MySQL查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39453202/

相关文章:

javascript - 'this' 在同一对象内返回 'Object' 或 'Window'

javascript - 通过type=file获取文件路径

javascript - JS : Audio Method not implemented in IE 10 of server 2008 R2

php - 从 MySQL 列获取数组

php - 无法在远程服务器上使用 Laravel 5.1 检索 url GET 参数

javascript - "Prevent"以编程方式单击元素

javascript - 成对查找重复值 - 选择下拉列表

javascript - 主干 View : function is undefined

php - 在 phpunit 中有没有一种方法可以为数组中的键断言两个值?

javascript - 如何将 jquery 值从选定的下拉列表传递到 Laravel 5.1 中的变量?