异步页面加载 - 如何将参数传递给回调?

时间:2009-04-06 03:05:26

标签: jquery asp.net-ajax

部分jQuery / ajax异步回调的东西仍让我感到困惑,我确信这只是因为我不太了解javascript。

尽可能简化代码,这就是我被困住的地方:

如果我创建一个id为“queuediv1”的空div,我可以用这样的页面方法的结果填充它。

$(document).ready(function() { 
    $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      url: "test12.aspx/GetHtmlTest", 
      //data: "{ 'Dividend': '" + $("#Dividend").val() + "' }", 
      data: "{}", 
      // Error! 
      error: function(xhr, status, error) { 
          // Boil the ASP.NET AJAX error down to JSON. 
          //var err = eval("(" + xhr.responseText + ")"); 

          // Display the specific error raised by the server 
          //alert(err.Message); 
          alert("AJAX Error!"); 
      }, 
       success: function(msg) { 
        $("#queuediv1").removeClass('isequeue_updating'); 
        $("#queuediv1").html(msg); 
            //an unorderd list with the tag "browserxx" was just inserted into the div 
        $("#browserxx").treeview(); 
      } 
    }); 
}); 

这很有效;它不是块,它让我完全控制错误处理。 但是,当我试图扩展它时,我遇到了麻烦。如果我想要更新页面的几个区域,我可以改变调用,以便使用正确的“数据”进行每次异步调用,但我无法告诉回调我想要它的控件的id填充。

将我的情况简化为仍然破碎的事情:

假设DOM中有4个div,我想要更新id的queuediv1,queuediv2,queuediv3和queuediv4。 我想尽可能多地重用代码。 虽然要更新的div的数量和ID实际上是动态的,但我认为这会有效:

$(document).ready(function() { 
for (i= 1;i<=4;i++) 
{ 
     var divname ="#queuediv"+i; 

    $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      url: "test12.aspx/GetHtmlTest", 
      // data would be populated differently so that each div gets its own result- for now it doesn't matter 
      //data: "{ 'Dividend': '" + $("#Dividend").val() + "' }", 
      data: "{}", 
      // Error! 
      error: function(xhr, status, error) { 
          // Boil the ASP.NET AJAX error down to JSON. 
          //var err = eval("(" + xhr.responseText + ")"); 

          // Display the specific error raised by the server 
          //alert(err.Message); 
          alert("AJAX Error!"); 
      }, 
       success: function(msg) { 
        $(divname).removeClass('isequeue_updating'); 
        $(divname).html(msg); 
        $("#somethingfromthemsg").treeview(); 
      } 
    }); 
} 
}); 

但这无法发挥作用,因为在调用成功时,范围是错误的,并且每个回调的divname已经等于“#queuediv4”。只有那个div得到更新(4x)。有没有办法将变量传递给回调?或者我只是在想错误的问题。

我确实在这里找到了类似于处理$ .getJSON异步调用的内容:http://thefrontiergroup.com.au/blog/tag/jquery

该网站讨论了将回调包装在另一个匿名函数中以保留调用变量。这种范围有意义,但我不知道如何形成$ .ajax调用的创建方式。

3 个答案:

答案 0 :(得分:1)

你可以将for循环的每个迭代包装在一个匿名函数中,如下所示:

$(document).ready(function() { 
for (i= 1;i<=4;i++) 
{ 
(function (){
     var divname ="#queuediv"+i; 

    $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      url: "test12.aspx/GetHtmlTest", 
      data: "{}", 
      error: function(xhr, status, error) { 
          alert("AJAX Error!"); 
      }, 
       success: function(msg) { 
        $(divname).removeClass('isequeue_updating'); 
        $(divname).html(msg); 
        $("#somethingfromthemsg").treeview(); 
      } 
    });
})(); 
} 
});

一个更简单的例子是:

<div id="output1"></div><div id="output2"></div><div id="output3"></div><div id="output4"></div><div id="output5"></div>
<script language="javascript">
for(var a=1; a<=5; a++) {
  (function (){
    var divName = "output" + a;
    var b = a;
    setTimeout(function(){document.getElementById(divName).innerHTML = b;}, 2000);
  })();
}
</script>

答案 1 :(得分:1)

请记住,JavaScript是一种真正的函数式语言,所有函数(匿名或非匿名)都是全功能closures,因此函数“外部”的变量仍然可用。

解决'传递参数'的通用方法是闭包的运行时构造:

function makeSuccessFunc (divname) {
    return function (msg) {
        $(divname).removeClass('isequeue_updating'); 
        $(divname).html(msg); 
        $("#somethingfromthemsg").treeview(); 
    };
};

所以你可以这样做:

$(document).ready(function() { 
for (i= 1;i<=4;i++) 
{ 
     var divname ="#queuediv"+i; 

    $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      url: "test12.aspx/GetHtmlTest", 
      // data would be populated differently so that each div gets its own result- for now it doesn't matter 
      //data: "{ 'Dividend': '" + $("#Dividend").val() + "' }", 
      data: "{}", 
      // Error! 
      error: function(xhr, status, error) { 
          // Boil the ASP.NET AJAX error down to JSON. 
          //var err = eval("(" + xhr.responseText + ")"); 

          // Display the specific error raised by the server 
          //alert(err.Message); 
          alert("AJAX Error!"); 
      }, 
       success: makeSuccessFunc (divname)
    }); 
} 
});

答案 2 :(得分:0)