通过AJAX调用PHP随机化器的输出


Call output of a PHP randomizer via AJAX

当前设置:在同一个PHP文档中,我有一个PHP随机化器函数和调用该函数的HTML——一个单独的txt文档,其中包含PHP函数调用的字符串:

功能

<?php
function rand_line($fileName, $maxLineLength = 4096) {
  $handle = @fopen($fileName, "strings.txt");
  if ($handle) {
    $random_line = null;
    $line = null;
    $count = 0;
    while (($line = fgets($handle, $maxLineLength)) !== false) {
      $count++;
      if(rand() % $count == 0) {
        $random_line = $line;
      }
    }
    if (!feof($handle)) {
      echo "Error: unexpected fgets() fail'n";
      fclose($handle);
      return null;
    } else {
      fclose($handle);
    }
    return $random_line;
  }
}
?>

我使用:调用HTML中的函数

<?php echo rand_line("strings.txt");?>
<input type="button" value="Another String" onClick="window.location.reload()">

当多个用户访问页面并按下按钮以获得新状态时,这往往会很慢。

我想要实现的目标:

提高性能,使整个事情不那么繁重:也许随机化器不必要地复杂,例如,我可以使用AJAX调用,但如果可能的话,将字符串列表保留在strings.txt文件中,并与PHP脚本和HTML分离。

对不起,如果我不知道我在说什么。。。我不是一个熟练的程序员。只是一个偶尔把东西拼凑在一起的家伙:)

您真的不想使用window.location.reload();太可怕了。。。您不想刷新页面。。。

location.reload()发送一个全新页面(整个HTML)的http请求,然后你的浏览器不仅需要再次呈现整个HTML,你还必须通过网络从a点到B点传输更多重复的数据。

您应该只为您需要的数据发送HTTP请求(您不需要整个HTML,您在第一次访问页面时就加载了它)。

相反,使用XMLHttpRequest javascript库(AJAX)只请求一部分数据(在您的情况下=>随机字符串)

HTML:

<!DOCTYPE html>
<html>
<head lang="en">
    <script type="text/javascript">
        function loadDoc(url, cfunc) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    cfunc(xhttp);
                }
            };
            xhttp.open("GET", url, true)
            xhttp.send();
        }

        function randomLine(xhttp) {
            alert(xhttp.responseText);
        }
    </script>
</head>
<body>
<input type="button" value="Get random line" onClick="loadDoc('http://localhost:8080/myScript.php', randomLine)">
</body>
</html>

PHP:

myScript.php

<?php 
function rand_line($fileName, $maxLineLength = 4096) 
{ 
   ... 
}
echo rand_line("strings.txt");        
?>

*编辑#2*

功能齐全的脚本。通过PHP抓取初始字符串,并存储在数组中以供以后使用JavaScript。最小化呼叫数。

PHP从文件中抓取字符串;生成一个默认(随机)字符串,以及一个字符串数组,供以后与按钮一起使用。

/**
 * @input array $file
 * @return array (mixed) [0] => string, [1] => array
 */
$randomStringFromFile = function($file) {
    if (!$file) return false;
    /**
     * @return Removes carriage returns from the file
     *         and wraps $val with single-quotes so as
     *         to not break JavaScript
     */
    $add_quotes = function(&$val) {
        return str_replace("'n", "", "'$val'");
    };
    return [$file[rand(0, count($file)-1)], array_map($add_quotes, $file)];
};
$randomString = $randomStringFromFile( @file('strings.txt') ) ?: false;

JavaScript

<div id="string_container"><?php echo $randomString[0]; // defaults random string to page ?></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
    var arr = [<?php echo implode(',', $randomString[1]); ?>],
        setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length)];
};
</script>

把上面的内容放在你的页面上,你就可以开始了。

编辑(原件)

我们可以使用以下方法(最快方法)从等式中完全删除PHP:

<div id="string_container"></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
    var request = new XMLHttpRequest(),
        file = 'strings.txt';
    request.open('GET', file);
    request.onload = function() {
        if (request.status === 200) {
            var arr = request.responseText.split("'n"), /** assuming line breaks in file are standard carriage returns (Unix); "'r" if Windows */
                setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length-1)];
        }
    };
    request.send();
};
</script>

ORIGINAL w/PHP

我们可以进一步简化PHP,从等式中完全删除循环。

$randomStringFromFile = function($file) {
    if (!$file) return false;
    return $file[rand(0, count($file)-1)];
};
echo $randomStringFromFile( @file('strings.txt') ) ?: 'No worky!';

使用file()将返回数组中的内容,从而允许您简单地随机选择一个键并返回值。

注意在随机选择密钥时,$file[rand(0, count($file)-1)]的平均性能优于array_rand()(例如$file[array_rand($file)];)。微不足道,你是不是。。~0.0002s~0.0005s

您可以简化代码

function rand_line($fileName, $maxLineLength = 4096) {
    $f = file($fileName);
    $length = $maxLineLength + 1;
    do {
        $line = $f[array_rand($f)];
        $length = strlen($line);
    } while ($length > $maxLineLength);
    return $line;
}