asp.net Ajax异步刷新多次请,后一次覆盖前一次问题

方法一:

CS文件:

  protected void Button1_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(3000);
        this.ViewState["count"] = Convert.ToInt32(this.ViewState["count"])+1;
        this.Label1.Text =  ViewState["count"].ToString();
    }

aspx文件

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <%= DateTime.Now.ToString()%><br />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
            <asp:Button ID="Button1" runat="server" Text="获取时间" OnClick="Button1_Click" /> 
        </ContentTemplate>
    </asp:UpdatePanel> 

问题:多次点击按钮,如果第一次请求未返回,接着发送第二次请求,第一次请求结果会被覆盖掉。

解决:可以再页面中添加如下脚本

  var pageRequestMaganger = Sys.WebForms.PageRequestManager.getInstance();
     pageRequestMaganger.add_initializeRequest(function (sender, e) {
         if (pageRequestMaganger.get_isInAsyncPostBack()) {
            e.set_cancel(true);
         }
     });

 第一次请求未返回,则取消后续的异步请求。第一次请求完成,再发送第二次请求。

方法二:

通常是将xmlHttp 对象作为局部变量来处理,并且在收到服务器端的返回值后手动将其删除

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>多个异步对象</title>
<script language="javascript">   
function createQueryString(oText){
    var sInput = document.getElementById(oText).value;
    var queryString = "oText=" + sInput;
    return queryString;
}
function getData(oServer, oText, oSpan){
    var xmlHttp;   //处理为局部变量
    if(window.ActiveXObject)
        xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    else if(window.XMLHttpRequest)
        xmlHttp = new XMLHttpRequest();
    var queryString = oServer + "?";
    queryString += createQueryString(oText) + "&timestamp=" + new Date().getTime();
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
            var responseSpan = document.getElementById(oSpan);
            responseSpan.innerHTML = xmlHttp.responseText;
            delete xmlHttp;  //收到返回结果后手动删除
            xmlHttp = null;
        }
    }
    xmlHttp.open("GET",queryString);
    xmlHttp.send(null);
}
function test(){
    //同时发送两个不同的异步请求
    getData('9-5.aspx','first','firstSpan');
    getData('9-5.aspx','second','secondSpan');
}
</script>
</head>
 
<body>
<form>
    first: <input type="text" id="first">
    <span id="firstSpan"></span>
<br>
    second: <input type="text" id="second">
    <span id="secondSpan"></span>
<br>
    <input type="button" value="发送" onclick="test()">
</form>
</body>
</html>

转载来源:http://www.cnblogs.com/xugang/archive/2010/08/07/1794748.html

原文地址:https://www.cnblogs.com/you000/p/2815533.html