-1

想象一下第一次,数据不匹配并且 ajax 已经返回请求然后向表单发送错误消息,之后如果表单/输入没有更改,我如何停止 ajax 调用?

$("input[name=signup]").click(function(event) {

if ($(this).attr('type') == "submit" && $(this).attr('name') == "signup") {

        formValidate = function() {
            $.ajax({
                url:   "/ajax/req-signup.aspx",
                type: "post",
                dataType: "json",
                data: { ... },
                success: function(response) { ... }
            });
        }
        formValidate();
    }
event.preventDefault();
});
4

2 回答 2

1

添加一个全局变量

var allowAjax = true;

验证失败时将其设置为 false:

allowAjax = false;

更改表单中的内容时设置为 true

$("input").change(function () {
    allowAjax = true;
});

并在进行 ajax 调用时检查其状态:

if ($(this).attr('type') == "submit" 
   && $(this).attr('name') == "signup" 
   && allowAjax ) { ... }

或者,您可以在验证失败时禁用提交按钮,并在更改时启用它。

$(":submit").attr('disabled', 'disabled');

如果您不介意使用插件,请查看jQuery 禁用小部件,您可能会发现它更易于使用。

于 2013-01-23T17:34:03.180 回答
1

您可以仅在某些更改时绑定单击事件 - 然后在触发单击事件时取消绑定它(从而消除对全局可用变量的需要):

/* whenever an input changes on your form, bind click event */
$("SELECT INPUTS HERE").change(function (){
    /* unbind first to ensure the click event won't be registered/triggered multiple times */
    $("input[name=signup]").unbind("click").click(doSignup);
});

function doSignup(e){
    if ($(this).attr("type") == "submit" && $(this).attr("name") == "signup"){
        /* a successful click has happened - unbind click */
        $("input[name=signup]").unbind("click");

        /* do ajax call */
        $.ajax({
            url:   "/ajax/req-signup.aspx",
            type: "post",
            dataType: "json",
            data: { ... },
            success: function(response) { ... }
        });
    };

    e.preventDefault();
};

从用户体验的角度来看,您可以通过几种方式来增强它。

  1. 每当您取消绑定单击或以其他方式向用户指示该按钮当前未处于可单击状态时,也要“禁用”该按钮。
  2. 不要在点击时取消绑定,而是考虑有条件地取消绑定。就像,在成功时解除绑定,但不要在错误时解除绑定,以便他们可以重试。此外,如果您正在进行输入验证,可能会在用户输入无效时解除绑定。等等。

希望有帮助!

于 2013-01-23T18:19:46.930 回答