简体   繁体   English

在javascript for循环中,在get方法执行之前执行

[英]in javascript for loop is executing before the get method executes

In the following example variable e contains all the selected clients from a select box, I am iterating them one by one in a for loop and passing them via jQuery's get method to take values according to client but the for loop is executing before get method ends and due to that it changes the value of val (which is next value). 在下面的示例中,变量e包含选择框中的所有选定客户端,我在for循环中逐个迭代它们并通过jQuery的get方法传递它们以根据客户端获取值,但for循环在get方法结束之前执行并且由于它改变了val的值(这是下一个值)。 How to resolve this problem ? 如何解决这个问题?

var e = document.getElementById("client");
for (var i = 0; i < e.options.length; i++) {
    if (e.options[i].selected) {
        var val = e.options[i].value;
        alert(val); // here it is coming normally

        $('#fund').append('<option value=' + select.options.length + '>---' + val + '----</option>');   
        $.get("listFundsForClient", { client: val }, function(data) {
            alert("2nd:" + val);// here it is taking next value due to for loop iteration
        });
    }
}

it is because here val is a closure variable, it can be re-written as 这是因为这里的val是一个闭包变量,它可以重写为

$('#client option:selected').each(function(){
    var $this = $(this), val =$this.val();
    alert(val); // here it is coming normally

    $('#fund').append('<option value='+select.options.length+'>---'+val+'----</option>');   
    $.get("listFundsForClient", {client: val}, function(data) {
        alert("2nd:"+val);// here it is taking next value due to for loop iteration
    });
})

You can make the call using $.ajax() to do it synchronously, like this: 您可以使用$.ajax()进行同步调用,如下所示:

$.ajax({
  url: myUrl,
  async: false,
  data: myData,
  success: function(data) {
    //stuff
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM