使用JavaScript在iframe中显示随机php页面

时间:2018-11-22 07:37:35

标签: javascript php

我想在iframe中加载.php。我在带有index.html的文件夹(具有iframe)中有10个以上的php文件。在此i框架中,当用户单击“下一步...”时,我想随机加载.php文件(不重复-如果显示的所有10个文件都显示消息“ No More”)。

我的index.html看起来像这样。该文件和所有.php文件都放在同一文件夹中。

 <!DOCTYPE HTML>
<html>
   <head>
      <title>Test</title>
      <link rel="stylesheet" type="text/css" href="main.cs" />
   </head>
   <body class="is-demo">
   <header id="demo-header">
         <div class="details">
            <div class="inner">
               <h1>one.php title</h1>
            </div>
         </div>
         <ul class="actions">
            <li><a href="index.php" ><span>Home Page</span></a></li>
            <li><a href="ten.php" class="button square previous"><span>Previous</span></a></li>

            <li><a href="javascript:choose_random_page()" class="button square next"><span>Next</span></a></li>
         </ul>
      </header>


      <script>
      var iframe = document.getElementById("demo-iframe");
var pages = ["one.htm", "two.htm", "three.htm", 
             "four.htm", "five.htm", "six.htm", 
             "seven.htm", "eight.htm","nine.htm",
             "ten.htm"];

function choose_random_page() {
   if(pages.length>0) {
      var r = Math.floor(Math.random(pages.length));

      var ranom_page = pages.slice(r,1);
      iframe.src = random_page;

   } else {
      alert("No more pages to load");
   }
}
      </script>

      <div id="demo-main">
         <iframe id="demo-iframe" src="" data-responsive="1">-</iframe>
      </div>

   </body>
</html>

2 个答案:

答案 0 :(得分:0)

将所有页面放入数组,混合,用javascript更改iframe src,然后从数组中排除页面。

var locations = ['a.php', 'b.php', 'c.php'];

for(var i = 0; i < locations.length; i++){
    // I put code for changing locations inside setTimeout, but you can change it with your logic.

    setTimeout(function(){
        document.getElementById('demo-iframe').src = locations[i];
    }, i * 1000)
}

答案 1 :(得分:-1)

一种达到目的的方法是将所有可能的页面以任何顺序排列在数组中。

然后,一旦函数触发选择随机页面,它应该执行以下操作:

a-检查pages数组是否仍然有可供选择的页面

b-选择0到数组中元素数量之间的随机索引

c-从该数组中切出元素,并使用值加载iframe源

var iframe = document.getElementById("demo-iframe");
var pages = ["one.php", "two.php", "three.php", 
             "four.php", "five.php", "six.php", 
             "seven.php", "eight.php","nine.php",
             "ten.php"];

function choose_random_page() {
   if(pages.length>0) {
      var r = Math.floor(Math.random(pages.length));
      
      var ranom_page = pages.slice(r,1);
      iframe.src = random_page;
      
   } else {
      alert("No more pages to load");
   }
}
<iframe id="demo-iframe">