Ajax Sending HTTP Request Twice?

2019-08-27 21:49发布

问题:

I am making A ajax login form great progress so far thanks to A few users on stack flow so far.

Now when I check all the fields out if it responds to enter being pressed it is working fine except when I tab to the submit button it is submitting the data twice according to the Chrome networking tab.

I think it is executing the .click function aswill as the .keycode function.

How can i say in the code if keycode enter is false and I click the button execute the function or if its true don't execute the .click function.

$(document).ready(function () {
    $('#field').keyup(function (e) {
        if(e.keyCode == 13) {
            //If enter is pressed vailidate the form
            $.ajax({
                url: 'ajax/check.php',
                type: 'post',
                data: {
                    method: 'fetch'
                },
                success: function (data) {
                    $('.chat .messages').html(data);
                }
            });
        };
    });
    $('#submit').click(function () {
        alert('Do something here this is just a test');
    });
});

回答1:

just add preventDefault and return false to the keyup function like that:

$('#field').keyup(function (e) {
    if(e.keyCode == 13) {
        //If enter is pressed vailidate the form
        e.preventDefault();
        $.ajax({
            url: 'ajax/check.php',
            type: 'post',
            data: {
                method: 'fetch'
            },
            success: function (data) {
                $('.chat .messages').html(data);
            }
        });
     return false;
    };       
});

This will prevent the form from submitting when users press ENTER.