2011-05-01 40 views
0

我有一个文本文件,用逗号(,)分隔亵渎词。现在我必须通过阅读这个文本文件来创建一个数组,每一个亵渎词应该被存储到数组中。如果有人知道如何做到这一点,请尽快回复我。 注意:我必须将这个文件存储在我选择的任何地方。我唯一要做的就是通过给文件的完整路径读取文本文件。这是没有必要的解决方案应该是在JavaScript中你可以回答jQuery或AJAX解决方案。 谢谢。如何通过javascript中的文本文件创建数组

+0

隐藏文件的输入控制是否使用ajax加载文件? – qwertymk 2011-05-01 05:04:22

回答

0

从技术上讲,你可以通过做 - http://www.phpletter.com/Our-Projects/AjaxFileUpload/

  1. 上传文件到您的服务器端代码,使用JSON数组解析回
 
    def upload_file  
     data = params['fileToUpload'].read 
     render :json => data.split(',') 
    end 
  1. 在你客户代码

< input type='file' size='25' name='fileToUpload'>

<button onclick='return ajaxFileUpload();'>Ajax Read</button> 

  1. 在你ajaxFileUpload()方法来处理返回data.split( '')
0

你能够操纵CSV阅读它之前手动档?我有一个类似的问题,但能够让生成它的人为它做一些事情,比如进行全局搜索/替换'\'然后将内容包装到JS字符串变量中。然后,我只包含新文件,就像其他任何JS文件一样。

Ex。

<!-- Modified CSV file with single JS variable --> 
<script type="text/javascript" src="csvFile.js"></script> 
<!-- Ben Nadel CSV Parser and any other custom code --> 
<script type="text/javascript" src="parseCsv.js"></script> 

原始CSV:

word,"multiple words",apostrophe's 

修改JS CSV:

var csvData = 'word,"multiple words",apostrophe\'s'; 

然后我用张贴samccone本·纳德尔链接做实际的解析。

1

这里是一个jQuery + AJAX解决方案,您可以使用

//HTML 
<input id="file" type="file" /> 
<input type="button" id="load" value="Load CSV" /> 

//JavaScript/jQuery 
$(function() { 

    //Stop caching if csv is likely to change often (change $.get to $.ajax) 
    $.ajaxSetup({ 
    cache: false 
    }); 

    $('#load').click(function() { 

    $.get($('#file').val(), function (content) { 
     var output = content.split(new RegExp(",|\r")) 
          .map(function (element) { 
      //Do what ever tidy up here 
      return $.trim(element).toLowerCase(); 
     }); 
     console.log(output); 
    }); 

    }); 

}); 

测试的CSV从http://en.wikipedia.org/wiki/Comma-separated_values

您可以通过使用这样的事情http://plugins.jquery.com/project/custom-file

相关问题