对,这对我来说很难,我想不通。我有 2 个 .php 文件(一个带有 iframe,另一个带有评论。所以我们分别称它们为 iframe.php 和 comment.php)。
在 iframe.php 文件中,我从数据库中获取随机 url,并将其作为 <iframe>
的 src :
$sql = mysql_query("SELECT url FROM address_book ORDER BY RAND() LIMIT 1")
在 comments.php 文件中,我从同一数据库表中获取随机 url:
$sql = mysql_query("SELECT comment FROM address_book ORDER BY RAND() LIMIT 1")
然后在 index.php 页面上我有按钮:
<button id="nextfLuky" onClick="viewNext();return false;">Randomize</button>
此按钮调用以下从 iframe.php 文件插入到 <div id="iframe"></div>
的 javascript 函数(位于 index.php 页面)。来自 comment.php 文件的评论也被插入到 <div id="comment"></div>
中。 (也位于 index.php 文件中)
这是 <button>
调用的 javascript
function viewNext()
{
$("#iframe").load("iframe.php");
$("#coment").load("coment.php");
}
问题是我需要从数据库中获取彼此相关的 url 和评论(如果我使用一个 .php 文件就可以做到,但我需要使用两个)。当我在两个不同的文件中随机获取它们时,当它们显示在 index.php 文件中时,它们彼此不相关。
如果我在两个不同的文件中随机获取 url 和评论,我如何才能获取彼此相关的 url 和评论?
补充:数据库表结构
______________________________________
id |int(11) |Auto Increment
______________________________________
url |varchar(255)
______________________________________
comment |text(1000)
______________________________________
最佳答案
好的,如果您更喜欢 JQuery,我将用 jquery 制作的解决方案替换 XmlHttp 解决方案。查看一下信息是如何传递的,我认为根据您的需要调整它并不难。
您只需创建一个 getUrl.php 文件来获取 url(我创建了一个用于测试目的)。 iframe.php 和 comment.php 将保持原样,*只需确保它们从 $_GET['url'].* 中获取随机 url。*
我再次注意到这是根据您当前设计的解决方案,而不是通用或最佳解决方案。
为了测试它,假设这是 index.php(你只需要这里的 viewNext() 其他代码用于测试):
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
function viewNext()
{
$.get("getUrl.php",null,
function(responseText)
{ $("#iframe").attr('src', 'iframe.php?url='+responseText);
$("#comment").load('comment.php','url='+responseText);
}
);//load ends
}//viewNext ends
</script>
</head>
<body onload="viewNext()">
<input type=submit value=next id="mySubmit" onclick="viewNext()"><br>
<IFRAME id="iframe" WIDTH=450 HEIGHT=100>
Ybrowser doesn't show IFRAME.
</IFRAME>
<div id="comment"></div>
</body>
</html>
然后是iframe.php(带有测试代码):
<?PHP
echo 'Hello from <font color=red>iframe.php</font> I got the url, here it is:<br>
<font color=blue>',$_GET['url'],'</font>';
?>
然后这是comment.php(带有测试代码):
<?PHP
echo 'Hello from comment.php I got the url, here it is:<br>
<font color=blue>',$_GET['url'],'</font>';
?
最后是 getUrl.php(复制粘贴 - 或包含 - 您的代码以在此处获取随机 url 并回显它!):
<?PHP
echo 'http://www.url',rand(1,9999),'.com';
?>
关于php - 如何同时在两个文档中从 MySQL 中获取相同的 Random() 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7698083/