如何安排ajax请求以5秒的延迟发送?

时间:2018-06-02 11:19:05

标签: jquery ajax

按下按钮后我想等待5秒,然后发送ajax请求。

现在,只要按下按钮,请求就会在第二个

中发送
<p id="test" rows="7" class="combo">
azmir:azmir
</p>
<button id="jsonp2" type="button" data-bind='click: registerClick'>Start</button>
<div class="aprovadas"></div>
$(document).ready(function () {
    $('.combo').each(function () {
        var input = '#' + this.id;
        var count = 0;
        $(count).show();
        combo(input, count);
        $(this).keyup(function () {
            combo(input, count)
        });
    });
});

function combo(field, count) {
    var number = 0;
    var matches = $(field).val().match(/(.+)/gm);

    if (matches) {
        number = matches.length / 1;
    }

    $(count).text(number + ' ');
}

$(document).ready(function () {
    $("#jsonp2").click(function () {
        var number = 0;
        var username = "";
        var password = "";

        $.ajax({
            url: "http://***",
            success: function (response) {
                var data = response.user_info;
                if (data.status.match("Active")) {
                    $(".aprovadas").append("My account work");
                }
            }
        });
    });
});

http://jsfiddle.net/qm3do4uu/552/

1 个答案:

答案 0 :(得分:1)

试试这个脚本。

$(document).ready(function() {
    $('.combo').each(function() {
    var input = '#' + this.id;
    var count = 0;
    $(count).show();
    combo(input, count);
    $(this).keyup(function() {
        combo(input, count)
    });
    });
});

function combo(field, count) {
    var number = 0;
    var matches = $(field).val().match(/(.+)/gm);
    if (matches) {
    number = matches.length / 1;
    }
    $(count).text(number + ' ');
}

$(document).ready(function() {
    $("#jsonp2").click(function() {
    var number = 0;
    var username = "";
    var password = "";
    setTimeout(function() {
        $.ajax({
        url: "http://***",
        success: function(response) {
            var data = response.user_info;
            if (data.status.match("Active")) {
            $(".aprovadas").append("My account work");
            }
        }
        });
    }, 5000);
    });
});

你应该在ajax调用之前使用setTimeout(function() { }, 5000);

fiddle link