类似的javascript代码?

时间:2012-02-28 01:44:53

标签: javascript

我不是很擅长javascript而且我想知道在javascript中这样做是否可行?

<?php

        $str = file_get_contents('splashes.txt');

        $splashes = explode("\n",$str);

        $ind = rand(1, count($splashes)) -1;


        echo $splashes[$ind];

?>

在javascript中等效的是什么?

2 个答案:

答案 0 :(得分:3)

使用XHR请求交换file_get_contents(),可能会被同源策略阻止。

使用explode()交换split()

使用rand()Math.random()count()属性交换length

答案 1 :(得分:1)

在使用JavaScript的网页上完全相同并不是一个好主意,因为如果它是一个巨大的文件,加载'splashes.txt'会浪费带宽。

是的,您希望在页面上显示随机播放。但是,如果'splashes.txt'是一个小文件,那么将它转换为JavaScript数组要好得多,例如。

var splashes = [
    'splash 1',
    'splash 2',
    ...
];
var splashIdx = Math.floor(Math.random() * splashes.length);
alert(splashes[splashIdx]);

如果'splashes.txt'是一个巨大的文件,只需用PHP读取它(与你问题中的代码完全相同),然后用XHR加载它(需要jQuery)。 e.g。

$.get('/get_splash.php', function(data) {
    alert(data);
)