简体   繁体   English

将数据导入 HTML 文件中的脚本的最简单方法

[英]Simplest Way to Import Data into Script in HTML File

I have a script in my HTML file that I use to generate a drop-menu.我的 HTML 文件中有一个脚本,用于生成下拉菜单。 Right now the contents of the drop-menu are hardcoded via an array I define within the script, like so:现在,下拉菜单的内容是通过我在脚本中定义的数组进行硬编码的,如下所示:

  <script>
    let select = document.getElementById("selectJob");
    let options = ["Job 1", "Job 2", "Job 3", "Job 4", "Job 5"]; // Hard-coded array
    for (let i = 0; i < options.length; i++) {
      let opt = options[i];
      let a = document.createElement("a");
      a.textContent = opt;
      a.setAttribute('href', '#');
      a.addEventListener('click', () => {
        populateJobVal(opt)
      });
      a.setAttribute('class', 'btn btn-link');
      let li = document.createElement("li");
      li.appendChild(a);
      select.appendChild(li);
    }

    function populateJobVal(val) {
      document.getElementById("selection").value = val;
    }
  </script>

What I'd like to know is, what is the simplest way to import that data from an external file?我想知道的是,从外部文件导入数据的最简单方法是什么? If, for instance, I have an external JS file that returns an array, how do I import that in here and use it within my script in place of the hard-coded array?例如,如果我有一个返回数组的外部 JS 文件,我如何在此处导入它并在我的脚本中使用它来代替硬编码的数组?

Maybe with an Ajax call?也许与 Ajax 通话?

const response = await fetch('http://example.com/jobs.json');
const options = await response.json();
for (let i = 0; i < options.length; i++) {
// etc.

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch请参阅https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM