簡體   English   中英

ajax提交后如何防止頁面刷新

[英]How to prevent page from refreshing after ajax submit

我剛開始在我的工作中使用 Ajax 功能,我對它不是很熟悉。 我有這個問題,當我提交數據時,它在不刷新頁面的情況下提交,但是在第二次嘗試提交時,頁面在提交前刷新。 我已經使用 e.preventDefault() 來防止頁面刷新,但它對我不起作用。 似乎有些事情我做得不對。

這是我的 Ajax 代碼

<!--AJAX PROCESS TO SUBMIT CHECKED COURSES-->
    $(document).ready(function(){
        loadNewCourse();
        loadDelTable();
        $('#submit').click(function(){
            $('#form').submit(function(e){ 
            e.preventDefault();
                var in_arr = [],
                    name = ("<?php echo $_SESSION['name']?>"),
                    email = ("<?php echo $_SESSION['email']?>"),
                    regno = ("<?php echo $_SESSION['regno']?>"),
                    level = ("<?php echo $_SESSION['level']?>"),
                    dept = ("<?php echo $_SESSION['dept']?>"),
                    semester = ("<?php echo $_SESSION['semester']?>");
                    $('.inChk').each(function(i){
                        var checked = $(this).is(':checked');
                        if(checked){
                            in_arr.push($(this).val());
                        }
                    });
                    $.ajax({
                    url: 'submit.php',
                    type: 'POST',
                    cache: false,
                    async: false,
                    data: {
                        post_inId : in_arr,
                        name : name,
                        email : email,
                        regno : regno,
                        level : level,
                        dept : dept,
                        semester : semester
                        },
                    success: function(data){
                        loadNewCourse();
                        loadDelTable();
                        // setTimeout(function(){
                        //     $('#regModal').modal('hide');
                        // }, 1000);
                        $('body').removeAttr('style');
                        $('#regModal').removeAttr('style');
                        $('.modal-backdrop').remove();
                        swal({
                            // "Success", "Registration successful", "success"
                            position: "top-end",
                            type: "success",
                            title: "Registration successful",
                            showConfirmButton: false,
                            timer: 2000
                        })
                    },
                    error: function(data){
                        swal("Oops...", "Registration failed.", "error");
                    }
                });
            });
        });

////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#deleteCheck').click(function(){
    $('#delform').submit(function(e){
    e.preventDefault();
        var id_arr = [],
            regno = ("<?php echo $_SESSION['regno']?>"),
            level = ("<?php echo $_SESSION['level']?>");
        $('.delChk').each(function(i){
            var checked = $(this).is(':checked');
            if(checked){
                id_arr.push($(this).val());
            }
        });
        swal({
                title: "Are you sure you want to delete selected courses?",
                text: "You can add these courses by registering again!",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes, delete!",
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger',
                closeOnConfirm: false
            },
            function(isConfirm){
                if(isConfirm){
                $.ajax({
                    type: "POST",
                    url: "submit.php",
                    data: {
                        post_id : id_arr,
                        regno : regno,
                        level : level
                        },
                    cache: false,
                    async: false,
                    success: function(data){
                        // console.log(data);
                        loadDelTable();
                        loadNewCourse();
                        swal({
                                // "Success", "Registration successful", "success"
                                position: "top-end",
                                type: "success",
                                title: "Delete successful",
                                showConfirmButton: false,
                                timer: 2000
                            })
                    },
                    error: function(data){
                        swal("Oops...", "Delete failed.", "error");
                    }
                });
            }else{
                // alert('isNotConfirm and is not success');
                swal("Oops...", "Delete failed", "error");
            }
        });
        return false;
///////////////////////////////////////////////////////////////////////////////////////////
    });
});

    function loadNewCourse(){
        $.ajax({
            url: 'processReg.php',
            type: 'POST',
            cache: false,
            async: false,
            data: {
                loadit : 1
            },
            success: function(disp){
                $("#reveal").html(disp).show();
            }
        });
    }
    
    function loadDelTable(){
        $.ajax({
            url: 'delete_tbl.php',
            type: 'POST',
            cache: false,
            async: false,
            data: {
                loadDel : 1
            },
            success: function(deldisp){
                $("#showRegtbl").html(deldisp).show();
            }
        });
    }
});

這是顯示提交數據的頁面

 <div class="" style="margin:auto;margin-top:0;text-align:center">
            <div class="" >
                <h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
                <p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><a href="#regModal" data-toggle="modal" data-target="#regModal"><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></a></p>
            </div>
        </div><br>
            <!--Display Courses that are available-->
                <span id="reveal"></span>

            <!--Table to display courses registered-->
                <span id="showRegtbl"></span>
    </div>
</div>

我已經被困在這里超過 3 天了。 這里有人可以幫我嗎?

我認為您誤解了表單的提交甚至處理。

表單的默認操作即提交可以通過input type="submit"<button>

默認的

 <h2> Form default action </h2> <form action=""> <input type="hidden" id="someInput" value="hey"> <input type="submit" value="submit"> </form>

為了防止表單的默認操作,您可以做兩件事。

避免使用type="submit"或按鈕

做這樣的事情

 function customForm(){ alert("Hey this is custom handler, dont worry page will not refresh...!"); }
 <h2> Form with custom action </h2> <form action=""> <input type="hidden" id="someInput" value="hey"> <input type="button" value="submit" onclick="customForm()"> </form>

使用 event.preventDefault()

 $('#myform').submit(function(e){ e.preventDefault(); alert("custom handler with preventDefault(), no reload no worries...!"); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2> Form with custom handler using preventDefault() </h2> <form id="myform" action=""> <input type="hidden" id="someInput" value="hey"> <input type="submit" value="submit" onsubmit="customForm(this)"> </form>

如有任何疑問,請評論。

調用$("#form").submit(function() { ... })下次提交表單創建一個處理程序。 $("#submit").click()的處理程序中執行此操作是不正確的。 單擊提交按鈕將為下一次提交建立一個處理程序,但默認操作將立即提交表單,從而刷新頁面。 e.preventDefault()放在單擊處理程序中會阻止重新加載,但是您必須單擊兩次才能提交表單(這實際上不起作用,因為提交按鈕的默認操作是觸發提交事件,而您正在阻止它)。

只需為每個表單創建提交處理程序,而無需在點擊處理程序中進行。

$(document).ready(function() {
  loadNewCourse();
  loadDelTable();
  $('#form').submit(function(e) {
    e.preventDefault();
    var in_arr = [],
      name = ("<?php echo $_SESSION['name']?>"),
      email = ("<?php echo $_SESSION['email']?>"),
      regno = ("<?php echo $_SESSION['regno']?>"),
      level = ("<?php echo $_SESSION['level']?>"),
      dept = ("<?php echo $_SESSION['dept']?>"),
      semester = ("<?php echo $_SESSION['semester']?>");
    $('.inChk').each(function(i) {
      var checked = $(this).is(':checked');
      if (checked) {
        in_arr.push($(this).val());
      }
    });
    $.ajax({
      url: 'submit.php',
      type: 'POST',
      cache: false,
      async: false,
      data: {
        post_inId: in_arr,
        name: name,
        email: email,
        regno: regno,
        level: level,
        dept: dept,
        semester: semester
      },
      success: function(data) {
        loadNewCourse();
        loadDelTable();
        // setTimeout(function(){
        //     $('#regModal').modal('hide');
        // }, 1000);
        $('body').removeAttr('style');
        $('#regModal').removeAttr('style');
        $('.modal-backdrop').remove();
        swal({
          // "Success", "Registration successful", "success"
          position: "top-end",
          type: "success",
          title: "Registration successful",
          showConfirmButton: false,
          timer: 2000
        })
      },
      error: function(data) {
        swal("Oops...", "Registration failed.", "error");
      }
    });
  });

  ////////////////////////////////////////////////////////////////////////////////////////
  // PROCESS AJAX DELETE ON CHECKBOX SELECT
  $('#delform').submit(function(e) {
    e.preventDefault();
    var id_arr = [],
      regno = ("<?php echo $_SESSION['regno']?>"),
      level = ("<?php echo $_SESSION['level']?>");
    $('.delChk').each(function(i) {
      var checked = $(this).is(':checked');
      if (checked) {
        id_arr.push($(this).val());
      }
    });
    swal({
        title: "Are you sure you want to delete selected courses?",
        text: "You can add these courses by registering again!",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete!",
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        closeOnConfirm: false
      },
      function(isConfirm) {
        if (isConfirm) {
          $.ajax({
            type: "POST",
            url: "submit.php",
            data: {
              post_id: id_arr,
              regno: regno,
              level: level
            },
            cache: false,
            async: false,
            success: function(data) {
              // console.log(data);
              loadDelTable();
              loadNewCourse();
              swal({
                // "Success", "Registration successful", "success"
                position: "top-end",
                type: "success",
                title: "Delete successful",
                showConfirmButton: false,
                timer: 2000
              })
            },
            error: function(data) {
              swal("Oops...", "Delete failed.", "error");
            }
          });
        } else {
          // alert('isNotConfirm and is not success');
          swal("Oops...", "Delete failed", "error");
        }
      });
    return false;
    ///////////////////////////////////////////////////////////////////////////////////////////
  });

  function loadNewCourse() {
    $.ajax({
      url: 'processReg.php',
      type: 'POST',
      cache: false,
      async: false,
      data: {
        loadit: 1
      },
      success: function(disp) {
        $("#reveal").html(disp).show();
      }
    });
  }

  function loadDelTable() {
    $.ajax({
      url: 'delete_tbl.php',
      type: 'POST',
      cache: false,
      async: false,
      data: {
        loadDel: 1
      },
      success: function(deldisp) {
        $("#showRegtbl").html(deldisp).show();
      }
    });
  }
});

如果您在同一個表單中有多個提交按鈕,您應該為每個按鈕分配click處理程序,但為表單創建submit處理程序。

感謝大家的幫助。 我最后進行了一些調試,通過從添加和刪除腳本中刪除表單標簽,然后將它們包含在顯示提交數據的頁面中,我能夠解決這個問題。 像這樣...

<div class="" style="margin:auto;margin-top:0;text-align:center">
            <div class="" >
                <h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
                <p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><a href="#regModal" data-toggle="modal" data-target="#regModal"><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></a></p>
            </div>
        </div><br>
  <!--Display Courses that are available-->
<form id='form' action='POST' href='#'>
   <span id="reveal"></span>
</form>

<!--Table to display courses registered-->
<form id='delform' action='POST' href='#'>
   <span id="showRegtbl"></span>
</form>
    </div>
</div>

有沒有更合適的方法來做到這一點,或者這沒問題? 感謝您到目前為止的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM