2017-05-26 90 views
0

我有兩個.txt文件,我試圖從中創建組合。我試圖把每個文件都放到一個數組中,因爲每個單詞都被換行符隔開。問題是,當我運行$.get時,它不會將任何信息保存到陣列。這裏是我的代碼:jQuery將文件行存儲到數組

<html> 
    <head> 
     <title>Email Validator</title> 
     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
    </head> 
    <body> 
     <span id="runtime"></span> 
     <table class="results"> 
      <tr> 
       <td>First Name</td> 
       <td>Last Name</td> 
      </tr> 
     </table> 
     <script> 
      //pull firstnames and store to array 
      var firstnames = new Array(); 
      $.get('first.txt', function(data){ 
       firstnames = data.split("\n"); 
      }); 

      //pull lastnames and store to array 
      var lastnames = new Array(); 
      $.get('last.txt', function(data){ 
       lastnames = data.split("\n"); 
      }); 

      var fn, ln; 
      //firstnames 
      $.each(firstnames , function(findex, fvalue) { 
       fn = fvalue; 
       //lastnames 
       $.each(lastnames , function(lindex, lvalue) { 
        ln = lvalue; 
        $("table.results").appendTo("<tr><td>" + fn + "</td><td>" + ln + "</td></tr>"); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

回答

0

$ .get()是一個AJAX調用,這意味着它是異步的。每當$ .get完成時就會發生data.split()行,而不一定在$ .each塊之前。

既然你需要建立兩個異步調用,您可以嘗試嵌入:

 //pull firstnames and store to array 
     var firstnames = new Array(); 
     var lastnames = new Array(); 
     $.get('first.txt', function(data){ 
      firstnames = data.split("\n"); 

      //pull lastnames and store to array 
      $.get('last.txt', function(data){ 
        lastnames = data.split("\n"); 

        // Process your two arrays here 
      });  
     }); 
0

有你的代碼的幾個問題。 當您想要依賴多個ajax調用的結果時,可以使用$.when。其中一個方法可以是:

$.when(first, last).then(successCallBackFn, failureCallBackFn); 

何處來自firstlast?那麼,他們可以調用$不用彷徨像下面的結果:

var first = $.get('first.txt', function(data){ 
       firstnames = data.split("\n"); 
      }); 

同樣last

var last = $.get('last.txt', function(data){ 
       lastnames = data.split("\n"); 
      }); 

最後,使用$。當象下面這樣:

$.when(first, last).then(successCallBackFn, failureCallBackFn); 

      function successCallBackFn(firstNames, lastNames) { 
       var fn, ln; 
       //firstnames 
       $.each(firstnames, function (findex, fvalue) { 
        fn = fvalue; 
        //lastnames 

        $.each(lastnames, function (lindex, lvalue) { 
         ln = lvalue; 
         $("table.results").append("<tr><td>" + fn + "</td><td>" + ln + "</td></tr>"); 
        }); 
       }); 
      } 

      function failureCallBackFn() { 
       console.log('failed'); 
      } 

也。請注意,您需要使用append而不是appendTo在行$("table.results").append

相關問題