programing

사용자가 폼을 제출할 때 언로드 전 액션을 비활성화하려면 어떻게 해야 합니까?

stoneblock 2023. 3. 5. 09:26

사용자가 폼을 제출할 때 언로드 전 액션을 비활성화하려면 어떻게 해야 합니까?

작은 코드가 하나 있어요

<script>
$(window).bind('beforeunload', function() {
  $.ajax({
    async: false,
    type: 'POST',
    url: '/something'
    });
  });
</script>

유저가 송신 버튼을 눌렀을 때에, 이 요구를 무효로 하려면 어떻게 하면 좋을까요.

기본적으로 여기와 같은 SO입니다.질문을 하고 페이지를 닫기로 결정하면 경고 창이 나타나지만 양식을 제출할 때는 그렇지 않습니다.

를 사용한 콜beforeunload이벤트 핸들러:

$('form#someForm').submit(function() {
   $(window).unbind('beforeunload');
});

양식이 제출되지 않도록 하려면 다음 행을 추가하십시오.

   return false;

사용하다

$('form').submit(function () {
    window.onbeforeunload = null;
});

메인 송신 기능을 사용하기 전에, 이것을 확인해 주세요! (있는 경우) 확인해 주세요.

델은 다음과 같이 사용합니다.

문서 준비 상태에서는 Before unload 함수를 호출합니다.

$(document).ready(function(){
    $(window).bind("beforeunload", function(){ return(false); });
});

submit 또는 location.reload 전에 변수를 언바인드합니다.

$(window).unbind('beforeunload');
formXXX.submit();

$(window).unbind("beforeunload"); 
location.reload(true);

ASP의 Detect onbeforeunload를 찾고 있습니다.NET 웹 어플리케이션에서는 ASP를 사용하여 페이지에 입력 컨트롤이 변경되면 경고 메시지를 표시해야 합니다.마스터 페이지와 컨텐츠 페이지가 있는 NET.마스터 페이지에서 3개의 콘텐츠 플레이스 홀더를 사용하고 있으며 마지막 콘텐츠 플레이스 홀더는 폼 뒤에 있습니다.

<form runat="server" id="myForm">

그래서 폼 클로징 태그 이후와 바디 클로징 태그 전에 이 스크립트를 사용했습니다.

<script>
        var warnMessage = "Save your unsaved changes before leaving this page!";
        $("input").change(function () {
            window.onbeforeunload = function () {
                return 'You have unsaved changes on this page!';
            }
        });
        $("select").change(function () {
            window.onbeforeunload = function () {
                return 'You have unsaved changes on this page!';
            }
        });
        $(function () {
            $('button[type=submit]').click(function (e) {
                window.onbeforeunload = null;
            });
        });
    </script>

before unload는 바인딩에 관한 한 이 방법으로 확실하게 동작하지 않습니다.네이티브로 할당해야 합니다.

이 바인드와 언바인드가 잘 되지 않았습니다.jQuery 1.7 이후로는 이벤트 API가 업데이트 되어 있습니다.bind()/.unbind()는 하위 호환성이 유지되지만 선호하는 방법은 on()/off() 함수를 사용하는 것입니다.

 <!DOCTYPE html>
 <html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>
  <script type="text/javascript">
    $(function() {
        $('#form_verify').dirtyForms();
    })
  </script>
  <title></title>
 <body>
<form id="form_verify" action="a.php" method="POST">
    Firt Name <input type="text">
    Last Name <input type="file">
    <input type="submit">   
</form>

바인드를 사용하는 경우 다음을 사용합니다.

$('form').submit(function () {
    $(window).unbind('beforeunload');
});

모든 양식 제출에 적합합니다.

아주 오래된 질문이지만 다른 사람들에게 유용할 수 있습니다.

사용자가 수정해야 하는 형식의 오류가 발생하더라도 제출 핸들러가 호출되었기 때문에 단순히 "전송" 이벤트에서 "전송"을 분리하는 것은 나에게 작동하지 않습니다.따라서 사용자가 폼을 전송하려고 시도했다가 오류를 수신하고 다른 페이지를 클릭하면 경고 없이 나갈 수 있습니다.

여기 꽤 효과가 있을 것 같은 해결 방법이 있습니다.

(function($) {

    var attached = false,
        allowed = false;

    // catch any input field change events bubbling up from the form
    $("form").on("change", function () {
        // attach the listener once
        if (!attached) {
            $("body").on("click", function (e) {
                // check that the click came from inside the form
                // if it did - set flag to allow leaving the page
                // otherwise - hit them with the warning
                allowed = $(e.target).parents("form").length != 0;
            });

            window.addEventListener('beforeunload', function (event) {
                // only allow if submit was called 
                if (!allowed) {
                    event.preventDefault();
                    event.returnValue = 'You have unsaved changes.';
                }

            });
        }                
        attached = true;
    });

}(jQuery));

이 방법으로, 페이지를 나가기 위한 클릭이 양식 내부에서 발생한 경우(예: 제출 단추) 경고는 표시되지 않습니다.이 페이지에서 나가는 클릭이 양식 외부에서 발생한 경우 사용자에게 경고합니다.

언급URL : https://stackoverflow.com/questions/4787995/how-to-disable-beforeunload-action-when-user-is-submitting-a-form