简体   繁体   English

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

[英]In an HTML/JavaScript file, how can I select a data file to include?

I have written a graphing program, but each time it runs it should prompt the user for a data file to plot. 我已经编写了一个绘图程序,但是每次运行它都会提示用户输入要绘制的数据文件。 Here is a very simplified program that has the data file (Data.js) hard coded in line 7: 这是一个非常简化的程序,在第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>

... where Data.js contains: ...其中Data.js包含:

var endWidth = 200;
var endHeight = 150;

But I want to select the data file, something like this, perhaps: 但是我想选择数据文件,可能是这样的:

<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>

But I am having difficulty fitting the two pieces together in one file. 但是我很难将两个文件放到一个文件中。 Obviously it should first request the data file and then draw the graph using the file name stored in the "chosenFile" variable. 显然,它首先应请求数据文件,然后使用存储在“ chosenFile”变量中的文件名绘制图形。 I am new to HTML and JavaScript. 我是HTML和JavaScript的新手。

Thanks. 谢谢。

--- Edit --- -编辑-

Thanks for your response, @TheGr8_Nik. 感谢您的回复,@ TheGr8_Nik。 I incorporated it in this file: 我将其合并到此文件中:

<!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>

I ran this on a local Windows machine with Chrome browser. 我在装有Chrome浏览器的本地Windows计算机上运行了该程序。 Chrome caused huge problems by changing the file path to C:\\fakepath\\ and by complaining about "Cross origin requests are only supported for protocol schemes: http, .....". Chrome通过将文件路径更改为C:\\ fakepath \\并抱怨“协议格式仅支持跨源请求:http,.....”,引起了巨大的问题。 Changing to Firefox fixed those. 改用Firefox可以解决这些问题。

To get the script to work I deleted this line and its closing brace because the onload event didn't seem to be happening: script.onload = function () { 为了使脚本正常工作,我删除了此行及其script.onload = function () {括号,因为似乎未发生onload事件: script.onload = function () {

You can use js to inject a script tag in your html: 您可以使用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) );
      }
    });
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将我的 JavaScript 文件包含到 HTML 页面中? - How can I include my JavaScript file into an HTML page? 我如何使用javascript将文件的一部分包含在另一个文件中 - how can i include part of a file in another file with javascript 我如何将带有数组的json文件包含到javascript文件中? - How i can include json file with array in to javascript file? 如何通过javascript(jquery)将html元素的内容设置为php include文件 - how can I set the content of a html element via javascript (jquery) to php include file 作为更大的 Ruby on Rails 项目的一部分,我如何有条件地在 html.slim 文件中包含一些 Javascript? - How can I conditionally include some Javascript in an html.slim file, as part of a larger Ruby on Rails project? 我如何将我在file1.html(通过javascript的文件选择控件)中选择的文件获取到file2.php中进行处理 - How can I get a file I selected in a file select control in file1.html, trough javascript, into file2.php to be processed 如何通过单击按钮在页面中包含html文件? - How can I include an html file in my page by clicking on a button ? 如何正确将javascript文件包含到html中 - How to correctly include a javascript file into html 如何动态包含包含javascript的html文件 - How to dynamically include a html file containing javascript 如何使用Javascript包含/插入HTML文件 - how to include/insert HTML file using Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM