1

我真的需要了解在挂起时如何阻止请求 ajax。让我解释一个例子:

我有一个名为“share”的输入类型,当我写一些东西并按回车 ajax 获取结果并将其插入到 mysql 中。如果我这样做了很多时间按下回车按钮它需要更多的结果,比如我按下回车多少次,即使 php 中有一个控件。我认为是请求ajax的问题​​,因为我确定控制php是正确的。太感谢了。

这是示例代码:

形式

<input type="text" class="share">

JS

$.fn.enterKey = function (fnc) { // function for check when i press enter
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}

$('.share').enterKey(function() { // ajax request
    var comment = $(this);
    if (comment.val() != "") {
        $.ajax({
            type: "POST",
            url:  add_comment.urlRemove,
            data: "text=" + comment.val(),
            success: function(html) {
                comment.val('');
            },
            error: function(){
                alert('Error on ajax call');
            }
        }); 
    } 
    else {
        return false;
    }
});
4

1 回答 1

1

您可以设置一个变量来确定请求是否已经发送,如下所示:

var alreadySent = false;

$('.share').enterKey(function() {
    var comment = $(this);
    if (comment.val() != "") {   
        if(!requestSent) {
            // Set variable to true
            alreadySent = true;

            $.ajax({
                type: "POST",
                url:  add_comment.urlRemove,
                data: "text=" + comment.val(),
                success: function(html) {
                    // Set variable to false
                    alreadySent = false;
                    comment.val('');
                },
                error: function(){
                    // Set variable to false
                    alreadySent = false;
                    alert('Error on ajax call');
                }
           }); 
        }
    }
});
于 2013-09-11T20:15:38.000 回答