programing

Ajax 요청이 성공한 페이지 리디렉션

telebox 2023. 2. 26. 09:34
반응형

Ajax 요청이 성공한 페이지 리디렉션

클라이언트측 검증에 Ajax를 사용하는 폼이 있습니다.폼의 끝은 다음과 같습니다.

$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,

        success: function(result) {
            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();

            });

        }
    });

편집: 오류에 대한 mail3.php 파일입니다.

$errors=null; 

if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}

if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    //header ("Location: thankyou.html");
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html

} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

Ajax 요청이 성공하고 오류가 없는 경우 사용자를 Thank You 페이지로 리다이렉트 할 수 있는지 궁금합니다.이게 가능합니까?

고마워! 에이미트

물론이죠. 성공 기능의 끝에 다음과 같은 것을 넣으세요.

if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

서버가 응답을 반환합니다.no_errors에러가 없는 경우.

에러 체크를 몇 가지 실시해, 모든 것이 합격했을 경우는, 설정해 주세요.window.location사용자를 다른 페이지로 리디렉션합니다.

$.ajax({
    url: 'mail3.php',
    type: 'POST',
    data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,

    success: function(result) {
        //console.log(result);
        $('#results,#errors').remove();
        $('#contactWrapper').append('<p id="results">' + result + '</p>');
        $('#loading').fadeOut(500, function() {
            $(this).remove();

        });

        if ( /*no errors*/ ) {
            window.location='thank-you.html'
        }

    }
});

리다이렉트 할 수 있는 것은,success핸들러, 다음과 같습니다.

window.location.href = "thankyou.php";

또는 결과를 표시하므로 몇 초간 기다립니다. 예를 들어, 이것은 2초 동안 기다립니다.

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);
$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,

        success: function(result) {

            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();

            });

            if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

        }
    });

mail3.php 파일에서 {} catch {} 시도에서 오류를 트랩해야 합니다.

try {
    /*code here for email*/
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
}

그럼 네 안에success전화는 결코 성공으로 돌아오지 않기 때문에 당신의 오류에 대해 걱정할 필요가 없습니다.

다음 중 하나를 사용할 수 있습니다.window.location.href = "thankyou.php";닉이 말한 것처럼 당신의 성공 기능 안에 있어요

나는 다른 글에 정확한 상황을 게시했다.재투고.

죄송합니다. 위에 올라온 질문에 대한 답변이 아닙니다.

그러나 흥미로운 주제 --- AJAX를 사용할 때와 사용하지 않을 때입니다.이 경우 AJAX를 사용하지 않는 것이 좋습니다.

로그인 및 비밀번호의 간단한 예를 들어보겠습니다.로그인이나 패스워드가 일치하지 않는 경우는, AJAX 를 사용해 「Login Inrect」라고 하는 간단한 메세지를 보고하는 것도 좋습니다.그러나 로그인 및 비밀번호가 올바른 경우 사용자 페이지로 리다이렉트하기 위해 AJAX 함수를 콜백해야 하는 이유는 무엇입니까?

이런 경우에는 간단한 폼 제출을 사용하여 로그인 실패 시 Relogin으로 수정합니다.php는 Login과 동일합니다.Relogin.php?error=와 같은 URL에 GET 메시지가 포함된 php비활성 로그인...뭐 그런 거...

내 2센트만.:)

다음과 같이 할 수 있을 것 같습니다.

window.location = "your_url";

두 가지 방법으로 공격할 수 있을 것 같습니다.

1) 삽입window.location = 'http://www.yourdomain.com성공 함수에 넣을 수 있습니다.

2) 추가 Ajax 호출을 사용하여 페이지 요소(http://api.jquery.com/jQuery.get/의 jQuery documents에서 찾을 수 있는 추가 정보)에 이것을 주입합니다.

또 다른 옵션은 다음과 같습니다.

window.location.replace("your_url")
// Create lag time before redirecting 
setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

$errors=null; 

if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}

if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html
    // redirect
    setTimeout();
} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

언급URL : https://stackoverflow.com/questions/3513971/page-redirect-with-successful-ajax-request

반응형