LoginSignup
1
1

More than 3 years have passed since last update.

JavaScript テキストファイルからリストを読み込んでPOSTする

Last updated at Posted at 2019-06-15

テキストファイルから、キーのリストを読み込んでPOSTする。

イメージ
ezgif.com-gif-maker.gif

方法

テキストファイルから読み込んだ情報をformの要素として挿入する。
以下では、formのidを使ってsearchFormをの要素として挿入している。
その後、挿入したidを使用してデータをpost。(以下はjson形式でpostする例)

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <script type="text/javascript" src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
  <title>File 読み込みテスト</title>
</head>

<body>
<pre id="preview"></pre>
<input type="file" id="getfile" accept="text/*">

<form method="post" id="searchForm" name="searchForm">
  <input type="button" name="btn" value="テキストファイルの内容をpostする" onclick="funcSearch();">
</form>

<script>
  var file = document.querySelector('#getfile');
  file.onchange = function () {
    console.log("file reading...");
    var fileList = file.files;
    //読み込み
    var reader = new FileReader();
    reader.readAsText(fileList[0]);

    //読み込み後
    reader.onload = function () {
      console.log(reader.result.split('\n'));

      var ele = document.createElement('input');
      ele.setAttribute('type', 'hidden');
      ele.setAttribute('name', 'MidList');
      ele.setAttribute('id', 'target');
      ele.setAttribute('value', reader.result.split('\n'));
      document.searchForm.appendChild(ele);
      // 画面に出力
      document.querySelector('#preview').textContent = reader.result;
    };
  }

  function funcSearch() {
    // ファイル読み込みからセットした値をidを指定して取り出す
    const target = document.getElementById("target");
    var midList = target.getAttribute("value").split(",");

    // hashでセット。配列で送信したいのでjsonにする
    var data = {"MidList":midList};
    console.log(JSON.stringify(data));
    $.ajax({
      type: "post",
      url: "http://localhost:8080/sample",
      data: JSON.stringify(data),
      contentType: 'application/json',
      dataType: "json",
      success: console.log("ok")
    });
  };
</script>
</body>
</html>

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1