类似的javascript代码?
我对javascript不是很在行,我想知道在javascript中这样做是否可行类似的javascript代码?,javascript,Javascript,我对javascript不是很在行,我想知道在javascript中这样做是否可行 <?php $str = file_get_contents('splashes.txt'); $splashes = explode("\n",$str); $ind = rand(1, count($splashes)) -1; echo $splashes[$ind]; ?> javascript中的等价物是什么?
<?php
$str = file_get_contents('splashes.txt');
$splashes = explode("\n",$str);
$ind = rand(1, count($splashes)) -1;
echo $splashes[$ind];
?>
javascript中的等价物是什么?使用XHR请求交换
文件获取内容()
,该请求可能被同源策略阻止
<?php
$str = file_get_contents('splashes.txt');
$splashes = explode("\n",$str);
$ind = rand(1, count($splashes)) -1;
echo $splashes[$ind];
?>
用split()
交换explode()
用
Math.random()
交换rand()
,用length
属性交换count()
。用XHR请求交换file\u get\u contents()
,这可能会被同源策略阻止
用split()
交换explode()
用
Math.random()
交换rand()
,用length
属性交换count()
。用JavaScript在网页上做同样的事情不是一个好主意,因为如果是一个大文件,加载“splash.txt”会浪费带宽
是的,您希望在页面上显示一个随机飞溅。但是,如果“splash.txt”是一个小文件,那么将其转换为JavaScript数组就更好了,例如
var splashes = [
'splash 1',
'splash 2',
...
];
var splashIdx = Math.floor(Math.random() * splashes.length);
alert(splashes[splashIdx]);
如果“splash.txt”是一个大文件,只需使用PHP读取它(与您问题中的代码完全相同),然后使用XHR加载它(需要jQuery)。e、 g
使用JavaScript在网页上执行完全相同的操作不是一个好主意,因为如果“splash.txt”是一个大文件,那么加载它会浪费带宽 是的,您希望在页面上显示一个随机飞溅。但是,如果“splash.txt”是一个小文件,那么将其转换为JavaScript数组就更好了,例如
var splashes = [
'splash 1',
'splash 2',
...
];
var splashIdx = Math.floor(Math.random() * splashes.length);
alert(splashes[splashIdx]);
如果“splash.txt”是一个大文件,只需使用PHP读取它(与您问题中的代码完全相同),然后使用XHR加载它(需要jQuery)。e、 g
由于Javascript是客户端的,因此没有完全等同于
file\u get\u contents()
。为此,您必须使用AJAX之类的工具。否则,explode()。为此,您必须使用AJAX之类的工具。否则,explode()
(String.split(delimiter)
)和rand()
(我不知道等价物是什么)。文字解决方案: