【问题标题】:Loading .json files to a HTML template using a HTML form for specific .json file使用特定 .json 文件的 HTML 表单将 .json 文件加载到 HTML 模板
【发布时间】:2017-05-20 02:50:18
【问题描述】:

我有很多不同的 .json 文件,我想将它们的名称输入到 HTML 页面(本地)表单中,以便将此信息加载到表中。

我的 HTML 表单如下所示:

  <form>
    File: <input type="text" Id="file_name">
    <input type="submit" value="Load file" onclick="filltable()">
  </form>

我的表头是这样的:

<div class="container">
  <table class="table table-bordered table-striped table-hover">
    <thead>
    <tr>
      <th>Sample</th>
      <th>Variant</th>
      <th>Depth</th>
    </tr>
    </thead>
  </table>
</div>

我的 javascript 脚本是这样的:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>

  function filltable() {
    var name = document.getElementById("file_name").value +".json";
  };

  $.getJSON(name,function(stuff){
    var items = [];
    $.each(stuff, function(key, val){
      items.push("<tr>");
      items.push("<td id=''"+key+"''>"+val.sample+"</td>");
      items.push("<td id=''"+key+"''>"+val.variant+"</td>");
      items.push("<td id=''"+key+"''>"+val.depth+"</td>");
    });
    $("<tbody/>", {html: items.join("")}).appendTo("table");
  });


</script>

我还尝试将 .getJSON 代码嵌入到我的 filltable() 函数中,以便在单击提交按钮时调用它 - 但这不起作用。如果我更换:

"$.getJSON(name,function(stuff){"

与:

".getJSON("file1.json",function(stuff{"

然后它加载正常 - 我只想能够使用输入加载不同的文件。

【问题讨论】:

  • fillTable() 没有做任何事情,因为它在你做 var name = 之后结束。
  • 好的,但我确实得到了变量“名称”,就像我做 console.log 或警报(名称)一样,那么它就是我在输入中输入的任何内容 - 那么为什么,如果我嵌入 $.get .JSON 代码到那个函数中它不会填满表格吗?
  • 当我将 .json 文件放在文件路径中时,$get.JSON 代码可以正常工作——只是当我将它与 name 变量一起使用时就不行
  • 尝试使用从表对象调用的原生insertRow()
  • 还要确保在file_input 文本框中只输入file1 而不是file1.json

标签: javascript php jquery html json


【解决方案1】:

试试这个:

$('form').on('submit', function(){
  var name = document.getElementById("file_name").value +".json";
  $.getJSON(name,function(stuff){
    var items = [];
    $.each(stuff, function(key, val){
      items.push("<tr>");
      items.push("<td id=''"+key+"''>"+val.sample+"</td>");
      items.push("<td id=''"+key+"''>"+val.variant+"</td>");
      items.push("<td id=''"+key+"''>"+val.depth+"</td>");
    });
    $("<tbody/>", {html: items.join("")}).appendTo("table");
  });
  return false;

});

【讨论】:

  • 我已经尝试过了,它不起作用 - 我很困惑为什么变量 'name' 没有加载这个文件,因为它是通过输入表单获得的
  • 请转到jsfiddle.net/7wpnL/905并输入api.myjson.com/bins/rc3sb作为文件名
  • 这行得通 - 为什么我在浏览器上使用它时这行不通?
  • 现在可以使用了!!!谢谢 - 我的变量不正确 - 非常感谢!
猜你喜欢
  • 2020-12-28
  • 2016-04-23
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2019-01-07
相关资源
最近更新 更多