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

问题描述 投票:0回答:3

部分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调用的方式。

jquery asp.net-ajax
3个回答
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
投票

[请记住,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)
    }); 
} 
});

© www.soinside.com 2019 - 2024. All rights reserved.