对于我一直在开发的 Web 项目,我需要浏览一个 XML 文件,获取一些 SimpleXML 对象并将它们存储在一个数组中,然后获取一个随机的 SimpleXML 对象并打印一些有关它的信息。
我已经完成了那部分,它可以工作 - 但只有当我自己加载页面时。当我尝试通过 jQuery 的$('#div').load('somescript.php');
方法将它加载到另一个 HTML 页面时,我总是得到相同的结果,因为 PHPrand()
总是产生 0。
这里可能是什么问题?在自己的浏览器选项卡中运行完全相同的脚本会给我随机结果(这是我想要的),但是用 jQuery 和 Ajax 将它加载到另一个页面中会给我相同的结果。
是什么导致了这里的问题?
如果有帮助,这是我的代码:
GetBandData.php
<?php
$ChosenGenre = "edm";
$AlreadyLoadedBands = False; // Set to True if we've already loaded the array of bands to show the user.
$BandsToShow = array(); // The final array of bands to show the user.
$XMLRoot = simplexml_load_file('artists.xml'); // The root of all XML queries.
if ($AlreadyLoadedBands == False){ // If the bands haven't already been loaded into an array...
foreach($XMLRoot->band as $ThisBand){ // Iterate through the XML database, looking at all the bands.
if ($ThisBand->genre == $ChosenGenre){ // If the band's genre and the user's chosen genre match up...
array_push($BandsToShow, $ThisBand); // Add the current band to the array of bands to look at.
}
}
$AlreadyLoadedBands = True; // "Okay, we've already loaded the bands. No need to do it again."
}
$RandomBand = rand(0, count($BandsToShow) - 1); // Set $RandomBand as a random integer between 0 and the amount of bands we've found.
// Set $BandImLookingAt's indexes to a bunch of data about the band in the $RandomBand-th index of $BandsToShow.
$BandImLookingAt = array(
"BandName" => $BandsToShow[$RandomBand]->name,
"BandSafeName" => $BandsToShow[$RandomBand]->codesafe_name,
);
echo "<pre>";
var_dump($BandImLookingAt);
echo "</pre>";
?>
艺术家.xml
<root>
<band>
<genre>edm</genre>
<name>Chainsaw Police</name>
<codesafe_name>chainsawpolice</codesafe_name>
</band>
<band>
<genre>edm</genre>
<name>Guerrilla Warfare</name>
<codesafe_name>guerrillawarfare</codesafe_name>
</band>
<band>
<genre>edm</genre>
<name>SPENDV</name>
<codesafe_name>spenda</codesafe_name>
</band>
<band>
<genre>edm</genre>
<name>Byzanite</name>
<codesafe_name>byzanite</codesafe_name>
</band>
<band>
<genre>edm</genre>
<name>Hawf</name>
<codesafe_name>hawf</codesafe_name>
</band>
</root>
索引.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
function recp() {
$('#myStyle').load('GetBandData.php');
}
</script>
<a href="#" onClick="recp()" >One</a>
<a href="#" onClick="recp()" >Two</a>
<a href="#" onClick="recp()" >Three</a>
<div id='myStyle'>
</div>