gpt4 book ai didi

php - 实时页面更新

转载 作者:可可西里 更新时间:2023-11-01 00:50:30 24 4
gpt4 key购买 nike

我需要帮助,这就是我真正想要做的。我有两个文件。 “index.php”和“realtime.php” index.php 根据url 参数“country_code”显示来自特定国家的新闻,realtime.php 每2 秒更新一次新闻列表。我想要的是让 realtime.php 获取 index.php 的当前 url 参数,以便它只能根据 url 参数更新来自该特定国家/地区的新闻。我真的需要这个帮助。再次感谢你。index.php 的脚本

<script type="text/javascript">
$(document).ready(function () {
$.arte({'ajax_url': '../realtime.php?lastid='+$('.postitem:first').attr('id'), 'on_success': update_field, 'time': 1000}).start();
function update_field(data)
{
$("#realtimeupdate").html(data);
}
});

</script>

realtime.php 脚本

<?php

include"customDB.php";
$lastid = $_REQUEST['lastid'];
$query = 'SELECT count(*) as newpost FROM wp_posts WHERE country_code = "XXXXX" AND post_id > "'.$lastid.'"';
$result = mysql_query($query);
$rec = mysql_fetch_object($result);
if($rec->newpost){ ?>
<a href="" id="newpostlink">(<?php echo $rec->newpost; ?>) new posts</a>
<script type="text/javascript">document.title = '(<?php echo $rec->newpost; ?>) new posts'</script>
<?php } ?>

我想让raltime.php中country_code="XXXXXX"的值作为index.php的url参数值谢谢

最佳答案

在 Javascript 中访问查询字符串

首先,您需要获取作为查询字符串参数传递的“country_code”的值。您可以像这样使用 Javascript 来执行此操作:

var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);

while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();

(取自this SO question)

现在,urlParams 看起来像这样:

urlParams = {
country_code: 'US'
}

因此,您可以更改 AJAX 调用以添加此参数:

$.arte({'ajax_url': '../realtime.php?country_code='+urlParams.country_code+'lastid='+$('.postitem:first').attr('id'), 'on_success': update_field, 'time': 1000}).start();

现在它可以通过 $_GET['country_code'] 下的 PHP 获得。

在 PHP 中使用变量

现在您可以访问变量并在查询中使用它。

$country_code = mysql_real_escape_string($_GET['country_code']);
$query = 'SELECT count(*) as newpost FROM wp_posts WHERE country_code = "' . $country_code . '" AND post_id > "'.$lastid.'"';

请注意,我编写此代码是为了符合您现有的编码风格。它不是很干净,因此您可以考虑使用 $.param() 和 MySQLi 准备好的语句等助手来清理它。

关于php - 实时页面更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572043/

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