jquery js onbeforeunload我想在页面刷新或关闭后提交表单,但失败了

y0u0uwnf  于 12个月前  发布在  jQuery
关注(0)|答案(1)|浏览(130)

当用户刷新或关闭窗口时,我想将表单数据提交到数据库。我尝试了这个方法,但它不起作用。当刷新或关闭时,p demo 1将变为No。但刷新或关闭后将变为Yes。但sumbit部分未触发。我尝试了这两种方法,它们都不起作用document.getElementById(“all_questions”).submit(); $('#save').click();如果我点击提交按钮,它就可以工作,使用Django作为框架

<script>
    window.onbeforeunload = function(e){
    document.getElementById("demo1").innerHTML="No";
    document.getElementById("all_questions").submit();
    $('#save').click();
  }
</script>

<form method = "POST"  name = "answer_question" id="all_questions">
<p id="demo1">Yes</p>
data
<div class="save-item1"><button class="save-button" type="submit" id="save" name="Complete">Save</button></div>
</form>

字符串

l3zydbqr

l3zydbqr1#

由于onbeforeunload事件的异步性质,在页面刷新或关闭时可靠地提交表单可能具有挑战性。
使用navigator.sendBeacon方法,该方法设计用于在后台发送数据,即使在页面卸载期间也是如此

<script>
    window.addEventListener('beforeunload', function (e) {
        document.getElementById("demo1").innerHTML = "No";

        // Serialize form data
        var formData = new FormData(document.getElementById("all_questions"));
        var data = new URLSearchParams(formData);

        // Send data using navigator.sendBeacon
        navigator.sendBeacon("/your-submit-endpoint", data);
    });

    // If you also want to handle form submission on button click
    document.getElementById("all_questions").addEventListener('submit', function (e) {
        e.preventDefault(); // Prevent the default form submission
        document.getElementById("demo1").innerHTML = "No";

        // Serialize form data
        var formData = new FormData(this);
        var data = new URLSearchParams(formData);

        // Send data using navigator.sendBeacon
        navigator.sendBeacon("/your-submit-endpoint", data);
        
        // Optionally, you can redirect or perform other actions after form submission
    });
</script>

<form method="POST" name="answer_question" id="all_questions">
    <p id="demo1">Yes</p>
    data
    <div class="save-item1"><button class="save-button" type="submit" id="save" name="Complete">Save</button></div>
</form>

字符串

相关问题