2013-02-24 220 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); 
    // .... 
});