Ajax发送两次HTTP请求? [英] Ajax Sending HTTP Request Twice?

查看:426
本文介绍了Ajax发送两次HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,由于一些用户在堆栈流方面,我正在Ajax登录表单方面取得长足进步.

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

现在,当我检查所有字段是否响应输入被按下时,它运行正常,除了当我按提交"按钮时,它根据Chrome网络标签两次提交了数据.

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.

我认为它会像.keycode函数一样执行.click函数.

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

如果输入的keycode为false并且单击按钮执行该功能,或者如果为true则不执行.click函数,我该如何在代码中说

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');
    });
});

推荐答案

只需添加preventDefault,然后将false返回给keyup函数,如下所示:

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;
    };       
});

这将阻止用户按ENTER提交表单.

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

这篇关于Ajax发送两次HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆