簡體   English   中英

在HTML / JavaScript文件中,如何選擇要包含的數據文件?

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

我已經編寫了一個繪圖程序,但是每次運行它都會提示用戶輸入要繪制的數據文件。 這是一個非常簡化的程序,在第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>

但是我很難將兩個文件放到一個文件中。 顯然,它首先應請求數據文件,然后使用存儲在“ 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可以解決這些問題。

為了使腳本正常工作,我刪除了此行及其script.onload = function () {括號,因為似乎未發生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) );
      }
    });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM