2013-02-24 218 views
0

我有一個腳本,按訂單把網址變成一個iframe中:閱讀TXT文件中的數據轉換爲JavaScript陣列

<script type="text/javascript"> 
    $(document).ready(function(){ 
    var array = ['http://www.example1.come', 'http://www.example2.com', 'http://www.example3.com']; 
    var beforeLoad = (new Date()).getTime(); 
    var loadTimes = []; 
    $('#1').on('load', function() { 
     loadTimes.push((new Date()).getTime());     
     $('#1').attr('src', array.pop()); 
     if (array.length === 0) { 
      $.each(loadTimes, function(index, value) { 
       $("#loadingtime"+index).html(value - beforeLoad); 
      }); 
     } 
    }).attr('src', array.pop()); 
    }); 
    </script> 

我得到的URL列表txt文件。該文件中的URL被寫入一列(1列,每行從新行開始)。我如何可以替換JavaScript中的'var數組'與該txt文件的內容?

回答

3

這是基本要點,您希望在檢索文件之後嵌入您要運行的任何代碼,並在其中放置註釋。

$.get("your_url", 
     function(data) { 
      var array = data.split(/\r\n|\r|\n/) //regex to split on line ending 
      var beforeLoad = (new Date()).getTime(); 
      var loadTimes = []; 
      //.... rest of your code here 
     } 
); 

請注意,這並不做,如果該文件不存在任何錯誤處理,你可能要重寫它使用jQuery's "Promise" interface described here.

+0

+1佔所有不同的可能行尾。 – 2013-02-24 20:19:12

0

使用jQuery的get方法直接從服務器請求文件,或者使用get調用一個php腳本,將該文件解析爲友好的格式,如JSON。

$.get('file.txt'); 

如果您將url解析爲JSON格式,那麼當它被接收到時,您可以輕鬆使用url。

$.get('file.txt', function(data){ 
    obj = JSON.parse(data); 
    // .... 
});