我有以下格式的JSON数组:
[" url1.de"" url2.de"" url3.de" ...]
phpScript
while($row = $result->fetch_assoc()) {
echo "
<tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>";
$urlarray[]=$row["MusikURL"];
$zufall = array_rand($urlarray);
echo "
<br /> <b>URL:</b> " . $urlarray[$i]; // echo URL : www.url1.de URL:www.url2.de ...
$jsarray = json_encode($urlarray,JSON_UNESCAPED_SLASHES);
$i++;
}
echo $jsarray; // ["url1.de","url2.de"...
的JavaScript
var url = new Array();
var urlamount = ' <?php echo $i; ?>;';
url = ' <?php echo json_encode($jsarray); ?>;';
alert(urlamount);
alert(url); // "["url1.de","url2.de"...
alert(url[1]); // I expected he will alert url1.de but he only alert single letters...in this case 'u'
var audio = new Audio(url[x]);
audio.addEventListener('ended', function () {
this.currentTime = 0;
this.play();
}, false);
audio.play();
}
我尝试通过url获取网址[x] x应该是urlamount之间的随机值... 或者是否有其他方法可以将URL从$ urlarray []保存到JavaScript数组?
提前感谢!!
答案 0 :(得分:0)
使用以下代码更改您的javascript代码
var urlamount = '<?php echo rand(0,(sizeof($jsarray)-1)); ?>';
var url_json = '<?php echo json_encode($jsarray,true); ?>';
var url = $.parseJSON(url_json);
alert(urlamount);
alert(url[urlamount]);