在从数组中选择之前,如何确保为每个值完成ajax?

Obj*_*lay 1 api ajax jquery loops for-loop

所以我有一个在用户提交表单时调用的函数,然后执行jquery加载以根据其输入找到相应的歌曲并显示它.所有这一切工作正常,但我想将这些值存储在一个数组中并对它们做一些事情(现在警告只是为了调试).我的猜测是代码发送"未定义",因为它不会在检查数组之前等待ajax完成.那么,我该如何解决这个问题呢?代码如下:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
        //final step is to initialize an array outside the function, fill it in, 
        //then window.out on each part of the array
            function callMe() {
                var hold = new Array();

                for (var i = 0; i < 5; i++) {
                    var b = $('#song'+i).val();
                    var c = $('#artist'+i).val();
                    var d = b + " " + c;
                    $('#'+i).html("Loading...");
                    $('#'+i).load('getInfo.php', {term: d}, function(data){
                        //I have no clue why 5 keeps popping up
                        hold[i] = data;
                        // alert("The number"+i+":"+hold[i]);
                    });       
                }
                for (var i = 0; i<5; i++) {
                    alert(hold[i]);
                }
            }
            $(function() {
                $('form').submit(function() {
                    callMe();
                    return false;
                });
            });
        </script>
Run Code Online (Sandbox Code Playgroud)

Dip*_*mar 6

使用 .done()

$('#'+i).load('getInfo.php', {term: d}, function(data){
     hold[i] = data;
     // alert("The number"+i+":"+hold[i]);
}).done(function(){ /* code goes here */ }); 
Run Code Online (Sandbox Code Playgroud)

看这里