我正在使用 PHP 和 PHPRedis 连接到 Redis。
这很好用
$redis = new Redis();
$redis->connect('localhost', 6379);
$total = $redis->get('total');
假设 $total 现在为 1。然后我使用 Redis 客户端递增键“total”,使其值为 2。
但现在我希望用户在单击按钮时能够看到新值
<script type="text/javascript">
window.onload=function() {
$('#newTotal').click(function (event) {
<?php
$redis = new Redis();
$redis->connect('localhost', 6379);
$total = $redis->get('total');
?>
$("#updated").html("Total is now <?php echo $total; ?>");
});
}
</script>
但这并没有给出新的值。
如何连接以获取更新的值?
最佳答案
你要明白,PHP是运行在服务端的,jQuery是运行在客户端的。话虽如此,您将需要使用 AJAX。以下是一种快速的方法:
$('#newTotal').click(function (event) {
$.ajax({
url: 'yourPHPfile.php',
type: 'GET',
success: function(data) {
$("#updated").html("Total is now " + data);
}
});
});
并且在 yourPHPfile
$redis = new Redis();
$redis->connect('localhost', 6379);
$total = $redis->get('total');
echo $total; //this is seen as the "data" parameter in the AJAX success
关于javascript - 在客户端从 Redis 获取新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954751/