問題描述
假設有個網頁會透過 javascript AJAX 呼叫某個 PHP 檔,該 PHP 檔會用亂數 rand()
取得並回傳一數字給 AJAX call。
若在短時間內發出多個 javascript AJAX 呼叫,譬如 2 秒鐘內發出 200 次 AJAX,則有可能前 1 秒 (前 100 次呼叫) PHP 都回傳同一個數值,第二秒 (100 次) 也都回傳同一個數值。
解決方法
- Use
mt_rand()
instead ofrand()
. (We can see that mt_rand() is better than rand() in almost every aspect) - 在 $.ajax({JSON}) 內加上
cache: false
防止 browser cache - 在 $.ajax({JSON}) 內加上
url: "getData.php?rand="+Math.random()
,防止 browser cache
另一個可能的原因為 Random Seed 重複,但是那只會發生在舊版本的 PHP。
As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
source: http://php.net/manual/en/function.srand.php,