gpt4 book ai didi

PHP 在 Ajax 重新加载时不生成随机数

转载 作者:行者123 更新时间:2023-12-02 18:43:05 26 4
gpt4 key购买 nike

对于我一直在开发的 Web 项目,我需要浏览 XML 文件,获取一些 SimpleXML 对象并将它们存储在数组中,然后获取随机 SimpleXML 对象并打印有关它的一些信息。

我已经完成了该部分,并且它可以工作 - 但仅当我自行加载页面时。当我尝试通过 jQuery 的 $('#div').load('somescript.php'); 将其加载到另一个 HTML 页面中时方法,我总是得到相同的结果,如 PHP 的 rand()总是产生 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>";
?>

artists.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>

index.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>

最佳答案

尝试设置

$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});

或者将随机数粘贴到GetBandData.php?{{random}}

关于PHP 在 Ajax 重新加载时不生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16683399/

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