你如何阻止通过重复点击一个jQuery AJAX调用用户?用户、jQuery、AJAX

由网友(老巷枯井)分享简介:我有一个网页与下面的脚本I have a web-page with the following script Javascript的Javascriptfunction LinkClicked() {var stage = this.id;var stop = $('#ContentPlaceHolderMen...

我有一个网页与下面的脚本

I have a web-page with the following script

Javascript的

Javascript

function LinkClicked() {

    var stage = this.id;
    var stop = $('#ContentPlaceHolderMenu_txtDate').val();
    var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();

    $("[id$='spinner']").show();


    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: "...",
        data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
        success: function (data) {
            $("[id$='spinner']").hide();
            PlotData(data.d);

        },
        error: function () {
            $("[id$='spinner']").hide();
            alert("An error occured posting to the server");
        }
    });

}

我如何阻止多次点击,而在查询运行的用户?呼叫来自在网格的小区和不容易被禁用。理想情况下,我想没有禁用链路上的DOM做脚本的一种方式。

How do I stop the user from repeatedly clicking whilst the query is running? The call is from a cell in a grid and can't easily be disabled. Ideally, I'd like a way of doing it in the script without disabling the link on the DOM.

在这里,我点击了五次,你可以看到五个AJAX请求被发送。该页面应该禁用相同的呼叫被反复调用,而它已在运行。

Here I clicked five times, and you can see five AJAX requests are sent. The page should disable the same call being repeatedly invoked whilst it is already running.

在此先感谢。

推荐答案

您可以有一个外部变量跟踪状态

You could have an external variable tracking the state

var linkEnabled = true;
function LinkClicked() {
    if(!linkEnabled){
    return;
    }
    linkEnabled = false;
    var stage = this.id;
    var stop = $('#ContentPlaceHolderMenu_txtDate').val();
    var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();

    $("[id$='spinner']").show();


    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: "...",
        data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
        success: function (data) {
            $("[id$='spinner']").hide();
            PlotData(data.d);
            linkEnabled =true;

        },
        error: function () {
            $("[id$='spinner']").hide();
            alert("An error occured posting to the server");
            linkEnabled = true;
        }
    });

}

这也有,你可以选择启用该功能等功效,如果你想的好处,只有prevent重复Ajax调用。

This also has the advantage that you can choose to enable other effects of this function if you want, and only prevent the repeat ajax calls.

(注意,理想情况下,你会想坚持外部变量在关闭或命名空间,而不是使之成为一个全球性的)。

(Note that ideally you would want to stick the external variable in a closure or a namespace rather than making it a global).

阅读全文

相关推荐

最新文章