-1

好啊。请帮助修复我的 php 代码:这是代码:

<?php
$urls = array("http://www.site1.com",
"http://www.site2.com",
"http://www.site2.com");
$url = $urls[array_rand($urls)];
?>
<?php echo $url ?>

我需要通过单击链接或按钮一一回显每个数组项。所以它会在点击按钮 website2 后打印 website1。

我将此代码用于按钮:

$(document).ready(function() {
   $("#button").click(function () { 
   $("#frame").attr("src", "<?php echo $url ?>");
  });
});
4

5 回答 5

2

You are confusing PHP and JavaScript. PHP is run on the server before the page is delivered to the client. JavaScript is run on the client side after the page has been downloaded. It is therefore impossible for JavaScript to call PHP without making new request to the server.

You must ether store the PHP variable in JavaScript or load it by Ajax.

于 2013-06-13T15:02:34.903 回答
1
$urls = array("http://www.site1.com",
"http://www.site2.com",
"http://www.site2.com");
$url = $urls[array_rand($urls)];
echo '<script>'.'var urls = [];';
foreach($url as $key){
  echo 'urls.push('.$key.');';
}
echo '</script>';

然后是按钮:

$(document).ready(function() {
   $("#button").click(function () { 
   $("#frame").attr("src", urls.pop()");
  });
});
于 2013-06-13T15:09:16.443 回答
1

你不能访问PHP变量JavaScript

例如,您可以将数组存储在PHP数组JavaScript

$(document).ready(function() {

  <?php 
    $urls = array("http://www.site1.com", "http://www.site2.com", "http://www.site2.com");
    echo 'var sites = ["'.$urls[1].'","'.$urls[1].'","'.$urls[1].'"], i= 0;';
    //you will probably have to use for here
  ?>

   $("#button").click(function () {
      if (i > i.length) { i=0 }
      $("#frame").attr("src", sites[i]);
      i++;
   });

});
于 2013-06-13T15:07:53.860 回答
0

另一种解决方案是在服务器上使用 php 呈现可点击按钮,以便在下载页面后,该按钮已经存在于 html 代码中。

你可以使用这样的东西:

foreach($urls as $url) {
echo '<a href="$url"><input type="button" name="$url" value="$url"></a>';
}
于 2013-06-13T15:10:48.170 回答
0

假设您的第一个脚本位于 ajax/geturl.php 中
(请注意,使用脚本原样(随机)您可以获得相同的 url 两次。)

然后在您的页面上它应该是类似的东西
(当然前提是您有 JQuery)

$.get('ajax/geturl.php', function(data) {
   $("#frame").attr("src", data);
});
于 2013-06-13T15:12:09.817 回答