繁体   English   中英

PHP表单重定向不起作用

[英]PHP form redirect not working

我有一些输入的基本html形式。 我的文件是“ form.php”,一旦数据发送到表单,我想做一个弹出窗口,然后重定向到我的主页。 无论出于何种原因,此代码

<script>
   document.getElementById("myForm").addEventListener("submit",function(){
   alertIt();
   return redirect(); 
   },false);

   function redirect(){
       window.location.replace = "index.html" ;
   }

   function alertIt(){
     alert("Thank you for your feedback!");
   }
</script>    

会导致正常工作的弹出窗口,但是一旦出现弹出窗口,它会将我带到"/form.php"而不是将我重定向到index.html。 任何帮助,将不胜感激。

您为什么不将表单发送到php文件,然后使用header("Location: index.html"); 重定向到索引?

您必须从事件处理程序中返回false ,以防止事件的默认操作,该操作将提交表单并重新加载结果。

document.getElementById("myForm").addEventListener("submit",function(){
    alertIt();
    redirect(); 
    return false;
},false);

另外,您的redirect功能是错误的。 window.location.replace是您应该调用的函数,而不是您分配的属性; 该属性是window.location.href

您需要告诉页面取消表单的默认操作。

使用现有代码,最简单的方法就是从redirect()函数返回false。

function redirect() {
    return false;
}

更好的方法可能是使用event对象的preventDefault()方法:

var submitHandler = function (e) {
    e = e || window.event;

    e.preventDefault();
    e.returnValue = false; //For older browsers

    alertIt();
    redirect();

    return false;
};

document.getElementById("myForm").addEventListener("submit", submitHandler, false);

function redirect(){
    window.location.href = "index.html";
}

function alertIt(){
   alert("Thank you for your feedback!");
}

请注意,您只是在替换窗口的位置,而不是告诉它重定向。

window.location.replace = "index.html"; //This sets the new location, but doesn't redirect

相比

window.location.href = "index.html"; //This causes the page to redirect immediately.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM