按鈕的ajax請求時,一次點擊兩次提交的問題


頁面中的按鈕的type是submit的: <input type="submit" value="Create" id="submit" />

ajax的請求,在JQuery中是:

    $( function () {
        $('#submit').click( function () {
             var createGenreForm = $('#createGenreForm');
             if (createGenreForm.valid()) {
                 var obj = {
                    Name: $('#Name').val(),
                    Description: $('#Description').val()
                };
                 var jsonSerialized = JSON.stringify(obj);
                $.ajax({
                    type: "POST",
                    url: createGenreForm.attr('action'),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: jsonSerialized,
                    success:  function (result) {
                        alert(result.Message);
                    },
                    error:  function (error) {
                        alert("There was an error posting the data to the server: " + error.responseText);
                    }
                });
            }
        });

    });

 發生兩次提交的原因是在執行完ajax請求后,並沒有阻止submit的行為,所以解決方法有兩種:

1、不使用type為submit類型的按鈕,而是使用type是button的按鈕。

2、在$('#submit').click函數中,最后加一行return false;,即可阻止submit。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM