【问题标题】:How can I refresh the results of a MySQL query without refreshing the page?如何在不刷新页面的情况下刷新 MySQL 查询的结果?
【发布时间】:2016-09-13 01:55:40
【问题描述】:

我想定期刷新一次查询的结果,比如每 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>

我的拍卖处理程序.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);
?>

我在网上阅读的很多东西并没有真正帮助我,而且我太初学者了,无法自己正确编写。我真的很难理解如何去做,以及如何在我的场景中实现它。

非常感谢任何建议。

【问题讨论】:

  • 您使用setTimeout 来“安排”您的ajax 调用。但是调用 window.location.reload() 无论如何都会强制重新加载整个页面,因此您必须使用 ajax 结果来更改页面的一部分,而不是重建整个页面。
  • 您的基本轮询选项是使用 setInterval 和 ajax 请求来获取当前出价
  • 好的,但我不确定该怎么做。
  • 您可以像现在一样在发布后安排重新加载页面。然后,当您开始工作时,您可以使用 ajax 转移到某些东西上。它大约有 3 行 javascript,所以你应该试一试。
  • 谢谢 - 但这向我展示了如何使用 ajax 提交表单。我已经在我的代码中工作的东西。我不确定 PHP 页面上有什么以及如何使用新值定位当前的出价 div

标签: javascript php jquery mysql


【解决方案1】:

离你不远了。

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

所以而不是:

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);

【讨论】:

  • 嗨,我已经尝试过了,但是在我刷新页面之前,所出价的任何内容都会从我的查询中消失。
  • 那么auction-handler.php 中的代码是您问题顶部的代码吗?
  • 嗨,抱歉,我不确定是否添加此代码,因为它与我正在尝试做的事情无关,我将使用此页面上的代码编辑问题。然而,这只是将出价放入 MySQL。
  • 好的,所以我查看了编辑,更新脚本似乎没有返回任何内容,它只是更新了表格。那么为什么不在插入后运行选择查询并检索新添加的行,+ 其他投标人添加的任何行。抱歉,我假设您已经这样做了,因此我的上述答案
  • 没问题。然后我的问题是该页面不会为其他所有人更新。抱歉,我发现做我想做的事非常困难。
【解决方案2】:

<div id="results">
	...
</div>

<script>
var time = 30000;
function autoRefresh()
{
	$.ajax({
		type: "POST",
		dataType: "HMTL",
		url: "auction-handler.php",
		data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
		success: function(data){
			$("#results").append(data);
		}
	});
}

setTimeout("autoRefresh()", time);
</script>

【讨论】:

  • 嗨,这看起来很接近 - 但我的问题(以及我在网上阅读时遇到的主要问题)是我可能一次更新多个出价。我的查询包含很多行,都有自己的 ID,所以我该怎么做 $("#results").append(data);如果我放入的 div 的每条记录的 id 都不同?
  • 您可以使用类 $('.results')... 或其他您想要的名称。
  • 使用您的响应 ajax,您可以将所有结果放在一个固定的 div 中,例如 id='results' 或 class='results'。但是,您每次都想要一个结果吗?
猜你喜欢
  • 2017-05-11
  • 2019-11-25
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2013-11-20
  • 2018-02-17
相关资源
最近更新 更多