在 n 秒内重定向并传递值

redirect in n seconds and pass values

本文关键字:重定向      更新时间:2023-09-26

我有页面A和B。页面 A 加载后,我将从用户那里获得输入。60 秒后,页面将自动重定向到页面 B。我用下面的代码做了,但值没有得到传递。

<html>
<head>
  <script type="text/javascript">
     function printVal()
     {
       printVal.counter--;
       document.getElementById("timer").innerHTML = printVal.counter;
       if(printVal.counter==0){
         window.location="next.php";
       }
     }
     function callfun()
     {
       setInterval(printVal,1000);
     }
     printVal.counter=61;
  </script>
</head>
<body>
  <input type="submit" value="Click Me" onclick="callfun()">
  <p id="timer"></p>
  <form method='post' action='next.php'>
     <input type='text' name='val'>
  </form>
</body>
</html>

我必须创建一个列表。用户在文本框中键入内容并按 Enter 键后,它应该会转到列表框中添加它。60 秒后,我希望将列表框中的值传递给 next.php。

更改

window.location不会将表单中的值提交到新位置。您必须提交表单。

if(printVal.counter==0)
    document.getElementsByTagName("form")[0].submit();
}

这是一个相当广泛的问题,可以尝试和有效地回答。

让我们从你的列表框开始:你问:once user types something in text box and press enter it should go and add in a list box. and after 60 seconds i want the values in the list box to be passed to next.php

如果用户不会对该列表框中的数据执行任何操作,为什么要将数据放在列表框中?所以我想你的思路是使用列表框来保存单独的值,然后你可以发布到下一个.php。

划定你说的值?好的,成交。让我们忽略json,ajax等等,用一些简单的普通javascript"教你如何钓鱼"。我会把模块化留给你!

作为 html 输入元素的 name-属性,我们还可以指定一个数组,如下所示:<input "name=itm[]">(您也可以在制作"listbox"时执行此操作,又名 <select name="var[]" multiple="yes"> )。让我们在列表中很好地显示它们。因此,每当您在文本区域/输入字段中按回车键时,都会将包含输入字段的列表项添加到表单中。

当计时器达到零时,您需要使用form.submit()提交表单(正如Andreas还指出的那样)。

这是一个简化但完全工作的示例:

<!DOCTYPE html><html><head><title>demo</title>
<script type="text/javascript">
window.onload=function(){
   itmLi=document.createElement('li');
   itmInp=itmLi.appendChild(document.createElement('input'));
   itmInp.type='text';
   itmInp.name='val[]';
   theItms=document.getElementById('theItems');
   fetchItem=function(el,evt){
      var itmAct, keyCode=(evt.which) ? evt.which : event.keyCode;
      if (keyCode == 13){
         itmAct=theItms.appendChild(itmLi.cloneNode(true));
         itmAct.firstChild.value=el.value;
         el.value='';
         return false;
      }
   };

   theTmr=document.getElementById('tmrOut');
   myTimer=function(){
      var t=Number(theTmr.innerHTML);
      if(t){
         theTmr.innerHTML=t-1;
         window.setTimeout(myTimer,1000);
      } else {
         theItms.parentNode.submit();
      }
   };
   window.setTimeout(myTimer,1000);
   document.getElementById('inpTxt').focus(); //sigh.. firefox does not work AGAIN.
};
</script>
</head><body>
<p>Time left: <span id="tmrOut">60</span></p>
<textarea id="inpTxt" onkeyup="return fetchItem(this,event);"></textarea>
<form id="theForm" method="post" action="next.php">
<ul id="theItems"></ul>
</form>
</body></html>

当然,您可以在此小提琴中找到一个工作演示(请注意,此演示运行 10 秒而不是 60 秒)。

现在你的 php-script next.php将收到一个变量:val(正如你已经命名的那样),但这个变量实际上是一个包含所有输入项目的数组(用回车键分隔)。
哒哒!

由于您只询问如何将变量传递给php,因此我的答案到此为止。如果你在接收php端需要帮助,我建议你先RTM。

祝你好运!!