在HTML / JavaScript文件中,如何选择要包含的数据文件?

时间:2015-08-03 12:40:23

标签: javascript html

我已经编写了一个图形程序,但每次运行它都会提示用户输入一个数据文件。 这是一个非常简化的程序,其中包含第7行硬编码的数据文件(Data.js):

<!DOCTYPE html>
<html>
  <head>
    <title>Warm-up</title>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script/>
    <script src="./Data.js"></script>

    <script>

      function drawHorizontalLine(c, startX, startY, endX, endY) {
        c.lineWidth = 3;
        c.strokeStyle = '#888';

        c.beginPath();
        c.moveTo(startX, startY);
        c.lineTo(endX, endY);
        c.stroke();
      }


      $(document).ready(function() {
        // Set the canvas width according to the length of time of the recording
        var myCanvas = document.getElementById("graph");
        var resultOfCalculation = 100;
        myCanvas.width += resultOfCalculation;

        graphWidened = $('#graph');
        var graphCanvas = graphWidened[0].getContext('2d');

        drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
      });
    </script/>
  </head>

  <body>
    <canvas id="graph" width="600" height="450">
  </body>
</html>

... Data.js包含的地方:

var endWidth = 200;
var endHeight = 150;

但我想选择数据文件,可能是这样的:

<input type="file" id="sourcedFile" />
<p id="chosenFile" ></p>

<script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0];

    if (f) {
      document.getElementById("chosenFile").innerHTML = f.name;
    } else {
      alert("Failed to load file");
    }
  }

  document.getElementById('sourcedFile').addEventListener('change', readSingleFile, false);
</script>

但是我很难在一个文件中将两个部分组合在一起。 显然它应首先请求数据文件,然后使用存储在“selectedFile”变量中的文件名绘制图形。 我是HTML和JavaScript的新手。

感谢。

---编辑---

感谢您的回复,@ TheGr8_Nik。我把它合并到这个文件中:

<!DOCTYPE html>
<html>
  <head>
    <title>Warm-up</title>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

    <input type="file" id="sourcedFile" />
    <p id="makeButtonGoAboveCanvas" ></p>

    <script type="text/javascript">
          var script;
      //
      // This function is called when sourcedFile changes as a result of user selection.
      // It inserts the code lines (actually graph data) contained in sourceFile into this location.
      //
      // Selected files must be in the same directory as this file.  (Why??)
      // When running on a local computer the file selection only works in Firefox browser.
      //
      function insertDataFromSelectedFile(evt) {
        //Retrieve the first (and only!) File from the FileList object
        var f = evt.target.files[0];

        if (!f) {
          alert("Failed to load file");
        }
        else {
          script,
              script_id = 'loaded_script',
              //file_name = "./Data.js";
              //file_name = "http://127.0.0.1:8887/Data.js";
              //file_name = this.value.replace("C:\\fakepath\\", "http://127.0.0.1:8887/");
              //file_name = this.value.replace("C:\\fakepath\\", "");
              file_name = f.name;

          script = document.createElement('script');
          script.id = script_id;    // assign an id so you can delete it after use

          delete(endWidth);                 // To test if sourcing worked
          script.src = file_name;          // set the url to load
          $('head').append( $(script) );    // append the new script in the header

          if (typeof endWidth == 'undefined') {
            alert ("endWidth is undefined. The selected file was not read or did not define endWidth");
          }
          else {
            drawGraph();
          }

          $('#'+ script_id ).remove();  // remove the last loaded script - Seems to be unnecessary
        }
      }

      function drawHorizontalLine(c, startX, startY, endX, endY) {
        c.lineWidth = 3;
        c.strokeStyle = '#888';

        c.beginPath();
        c.moveTo(startX, startY);
        c.lineTo(endX, endY);
        c.stroke();
      }

      function drawGraph() {
        // Draw the graph
        var myCanvas = document.getElementById("graph");
        var resultOfCalculation = 100;
        myCanvas.width += resultOfCalculation;

        graphWidened = $('#graph');
        var graphCanvas = graphWidened[0].getContext('2d');

        drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
        //drawHorizontalLine(graphCanvas, 10, 20, 400, 80);
      }

      document.getElementById('sourcedFile').addEventListener('change', insertDataFromSelectedFile, false);
    </script>
  </head>

  <body>
    <canvas id="graph" width="600" height="450">
  </body>
</html>

我在使用Chrome浏览器的本地Windows计算机上运行此功能。 Chrome通过将文件路径更改为C:\ fakepath \并抱怨“仅支持协议方案的交叉源请求:http,.....”,从而导致了巨大的问题。更改为Firefox修复了这些。

为了使脚本正常工作,我删除了这一行及其右括号因为onload事件似乎没有发生:script.onload = function () {

1 个答案:

答案 0 :(得分:0)

您可以使用js在html中注入脚本标记:

$( function () {
    $('#sourcedFile').on( 'change', function () {
      var script,
          script_id = 'loaded_script',
          file_name = this.value;

      // check if the name is not empty
      if ( file_name !== '' ) {
        // creates the script element
        script = document.createElement( 'script' );

        // assign an id so you can delete id the next time
        script.id = script_id;

        // set the url to load
        script.src = file_name;

        // when the script is loaded executes your code
        script.onload = function () {
          var myCanvas = document.getElementById("graph");
          var resultOfCalculation = 100;
          myCanvas.width += resultOfCalculation;

          graphWidened = $('#graph');
          var graphCanvas = graphWidened[0].getContext('2d');

          drawHorizontalLine(graphCanvas, 10, 20, endWidth, endHeight);
        };

        // remove the last loaded script
        $('#'+ script_id ).remove();
        // append the new script in the header
        $('head').append( $(script) );
      }
    });
  });