how to load data from text file to javascript array?

前端 未结 3 1102
失恋的感觉
失恋的感觉 2020-12-10 20:49

i have an array called items=[\"apple\",\"mango\",\"cherry\"];

i wonder how i can load the array data from text file instead of declaring it?the text f

相关标签:
3条回答
  • 2020-12-10 21:27

    Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.

    But one way to access the text file using jQuery would be

    jQuery.get('http://localhost/foo.txt', function(data) {
        var myvar = data;
    });
    
    0 讨论(0)
  • 2020-12-10 21:40
     var file = event.target.file;
     var reader = new FileReader();
     var txt=reader.readAsText(file);
     var items=txt.split(",");
    
    0 讨论(0)
  • 2020-12-10 21:45

    With jQuery you can do something like this

      $.get("textFile.txt", function(data) {
          var items = data.split(',');
      });
    

    You may need something like this though

    var items = data.replace(/"/g, '').split(',');
    

    This is a start.

    If this is a user input file then you may need to upload it before you work with it.

    0 讨论(0)
提交回复
热议问题