gpt4 book ai didi

jquery - 使用jquery从mysql获取数据

转载 作者:行者123 更新时间:2023-11-29 06:19:13 24 4
gpt4 key购买 nike

我想从 mySQL 获取一些数据,而不使用 jQuery 刷新页面。有人可以告诉我如果 mysql 表中的任何记录被更新,我如何获取数据。例如,以下代码从数据库中获取数字计数,如果有人在数据库中添加了一个数字并且该数字已更新,我如何在不刷新页面的情况下显示新数字?谢谢。

<?
$query = "SELECT number, name FROM members WHERE id=1";
$result = mysql_query($query);

$row = mysql_fetch_array($result);
$number = $row['number']; ?>

最佳答案

已经提到过两次了,但我还是想强调一下。您永远不会希望客户端能够直接访问数据库。这是一个严重的安全风险。

现在来解决问题。首先,您需要设置一个可以使用 ajax 请求的 PHP 文件。我们将其命名为 check.php,它将如下所示:

<?php
// include necessary files to enable connection to the database
$query = "SELECT number, name FROM members WHERE id=1";
$result = mysql_query($query);

$row = mysql_fetch_array($result);
$number = $row['number'];

// send correct content type header of json
header("Content-Type", "application/json");

// we create an array, and encode it to json
// then echo it out while killing the script
die(json_encode(array('numbers'=>$number)));

现在我们来看看 JavaScript。该解决方案与 Kyle Humfeld 的解决方案类似,但不会使用 setInterval,因为这是一个非常糟糕的做法。其背后的原因是 setInterval 不会关心 ajax 调用的状态,无论它是否完成。因此,如果服务器出现问题,您可能最终会收到堆叠请求,这并不好。

因此,为了防止这种情况发生,我们改为使用 ajax 方法的 success 回调( .getJSON 本质上是 .ajax 的简写)和 setTimeout 创建名为 polling 的东西:

$(function(){
// placeholder for request
var request = null;

// request function
var check = function() {
request = $.getJSON('check.php', function(data){
// this will log the numbers variable to the dev console
console.log(data.numbers);
// initiate a timeout so the same request is done again in 5 seconds
setTimeout(check, 5000);
});
});

// initiate the request loop
check();

// if you want to cancel the request, just do request.abort();
});

此外,还有一个更高级的解决方案,使用 comet server这会将数据从服务器推送到客户端,但在深入研究 comet 之前,您应该首先尝试让上述内容正常工作。如果您想了解该主题,我建议您看一下 APE .

关于jquery - 使用jquery从mysql获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com