在 Javascript 中使用 PHP 检索的打开 url

Opening url retrieved with PHP inside Javascript

本文关键字:url 检索 PHP Javascript      更新时间:2023-09-26

需要使用javascript打开$link,这是使用PHP从XML文件中检索的。代码如下:

<?php
$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location 
?>
<html>
<head>
    <title></title>
</head>
<body>
<script>
  $(document).ready(function(){
      window.open($link, "_blank"); // will open new tab on document ready
  });
</script>
</body>
</html>

你不能从javascript访问php变量。使用 php,您可以在服务器上渲染 html 和 javascript。因此,您需要将$link变量打印到页面上:

window.open("<?= $link ?>", "_blank");

请注意,短 echo 标签 <?= 只保证在 php 5.4+ 上可用,如果您坚持支持旧版本,请使用 <?php echo