2014-01-09 5 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>  

결과는하지만, 그것은 index.html을 저를 리디렉션 대신 "/form.php"에 저를 소요이 코드하십시오. 어떤 도움을 주시면 감사하겠습니다.

+0

'window.location.replace'? – Oleg

답변

1

에 비해?

+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를 반환하는 것입니다.

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!"); 
} 

는 단순히 리디렉션을 말하고, 윈도우의 위치를하지 대체하고 있습니다 :

function redirect() { 
    return false; 
} 

더 좋은 방법은 event 개체의 preventDefault() 방법을 사용할 수 있습니다.

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

왜 인덱스로 리디렉션하는 header("Location: index.html");를 사용하여 다음 PHP 파일로 양식을 보내하지 않습니다

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 코드 야 ... -1. – crush

관련 문제