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

在HTML/JavaScript文件中,如何选择要包含的数据文件?,javascript,html,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"><

我已经编写了一个绘图程序,但每次运行时都会提示用户输入一个要绘图的数据文件。 下面是一个非常简化的程序,在第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>
但是我想选择数据文件,类似这样的,也许:

<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>
但是我很难把这两件东西放在一个文件里。 显然,它应该首先请求数据文件,然后使用chosenFile变量中存储的文件名绘制图形。 我不熟悉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{

您可以使用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) );
      }
    });
  });

您可以使用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) );
      }
    });
  });

我认为您需要将图形绘制为readSingleFile函数的一部分,而不是在document.ready,否则绘制图形的代码将在页面加载时调用,并且不再调用。谢谢-您发现了我遇到的一个问题。我将尝试它。我认为您需要将图形绘制为readSingleFile函数的一部分,而不是n在document.ready,否则,绘制图形的代码将在页面加载时调用,不再调用。谢谢-您发现了我遇到的一个问题。我将尝试它。谢谢-非常有趣。调查$未定义和其他内容。@userPC-您必须将HTML文件头中的jQuery与Thanke-非常有趣。Investiga链接ting$未定义和其他内容。@userPC-您必须将HTML文件头中的jQuery链接到