2014-01-09 73 views
1

我有一些基本的html表單和一些輸入。我的文件是「form.php」,一旦數據發送到表單,我想做一個彈出窗口,然後重定向到我的主頁。無論出於何種原因,該代碼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。任何幫助,將不勝感激。

+0

'window.location.replace'? – Oleg

回答

1

你爲什麼不的形式發送到PHP文件,然後使用一個header("Location: index.html");重定向到索引?

+0

真棒。這工作得很好,謝謝! –

0

您必須從事件處理函數返回false以防止提交表單並重新加載結果的事件的默認操作。

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

此外,您的redirect功能是錯誤的。 window.location.replace是你應該調用的函數,而不是你指定的屬性;該物業是window.location.href

+0

啊好吧這是有道理的。我改變了這個方法以及window.location.replace,但它仍然將我重定向到form.php .... –

0

您需要告訴頁面取消窗體的默認操作。

使用您現有的代碼最簡單的方法來做到這一點,您只需從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. 
+0

這是什麼原因,反對票? – crush

+0

-1。爲什麼'window.location.replace =「index.html」;'?它取代了函數而不是調用它。 – Oleg

+0

@Oleg這不是我的代碼 - 這是OP的代碼...不是我的。 – crush