每次调用时,AJAX调用都会增加+1

时间:2012-05-07 15:37:47

标签: jquery ajax vb.net

我有一块JQuery AJAX,它调用返回字符串数据的VB.NET代码隐藏(类)。它抓取特定服务器上的一些最新统计信息。现在代码有效,但是第一次按下刷新按钮时,数据会被返回,屏幕上会显示“刷新”警告。

但如果我再次按下它,警告框“刷新”会显示两次,我再次点击三次!等等,直到超时开始。

它似乎来自AJAX调用而没有其他地方。我不知道什么可以称之为,我已经尝试删除成功后返回的数据,但没有快乐。关于什么可能导致这个或在哪里看的任何想法?

function RefreshServer(btn,div,id,ip) {

$('#aRefresh'+id).html("<img src=images/refreshServer.gif border=0 align=absmiddle />");
$("#"+btn).click(function() {
$.ajax({
  type: "POST",
  url: "Dashboard.aspx/refreshServerAJAX",
  timeout: 5000,
  data: "{'IP': '" + ip + "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    var substr = msg.d.split('%');
    $('#serverBox_mod'+id).html(" " +substr[0]);
    $('#serverBox_map'+id).html(" " +substr[1]);
    $('#serverBox_playing'+id).html(" " +substr[2] + "/" + substr[3]);
    $('#serverBox_img'+id).html("<img src=images/Maps/" + substr[4] + " height=80 width=120 border=0 style=margin-top:10px;margin-bottom:10px; />");
    $('#serverBox_title'+id).html(" " +substr[5]);
    $('#aRefresh'+id).html("Refresh");
    delete substr
    delete msg
    alert("Refreshed");  
  },
  error: function(msg) {
    $('#aRefresh'+id).html("Refresh");
    $('#serverBox_title'+id).html("Server didn't respond!, sorry about that. Please try again...");
  }
});
});  
}

3 个答案:

答案 0 :(得分:2)

我猜你每次调用函数时都会绑定click事件。所以它正在向服务器页面调用大量的ajax。因此,如果您希望保持代码结构并修复它,我将取消绑定已添加的click事件并再次绑定它。

function RefreshServer(btn,div,id,ip) {

  $("#"+btn).unbind('click');
  $("#"+btn).click(function() {
     //your ajax code is here
  });

}

答案 1 :(得分:1)

错误似乎不在这个特定的代码区域......但是看着它,似乎你在{{1}内设置click的{​​{1}}处理程序功能。正常情况下可能导致多次AJAX调用的原因是最简单的:您在同一事件上附加了多个事件处理程序。

现在,如果您多次在同一个$('#' + btn)实例上调用RefreshServer()函数,则会发生这种情况,因为该函数会分配处理程序。您的代码中是否有可能发生这种情况?我假设不知何故,每次点击,你都会以某种方式调用它,因此将一个事件处理程序的另一个实例附加到按钮。

答案 2 :(得分:0)

使用它来调用ajax函数一次:

var ajaxLoading = false;
$(document).ready(function() {
    $('#ajaxRequestor').click(function(e) {
        e.preventDefault();
        if(!ajaxLoading) {
            ajaxLoading = true;
            $('#ajaxContentPlaceholder').load('/path/to/content.html', 
                function() { 
                    ajaxLoading = false;
                }
            );
        }
    });
});
相关问题