【问题标题】:Populating dropdown with GET data from separate JS file使用来自单独 JS 文件的 GET 数据填充下拉列表
【发布时间】:2019-12-20 11:52:12
【问题描述】:

我继承了一个项目,原作者将他们的代码拆分为单独的 JS 文件。其中之一包含所有 GET 请求,例如 Departments、Category、Titles 等。

我在一个单独的文件index.js 中有一些用于自动完成下拉列表的代码,并且我想用部门结果填充下拉列表。我不太精通 JS 和我不确定我必须做什么才能“连接”文件并引用 Departments GET 请求。

index.js:

import "jquery";
import "jquery-autocomplete/jquery.autocomplete.css";
import "jquery-autocomplete/jquery.autocomplete.js";

function loadCombobox() {
    let depts = {
        "t1": "1",
        "t2": "2"
    } // added this as a test

    let deptsArray = $.map(depts, function(value, key) {
        return {
            value: value,
            data: key
        };
    })
    console.log(deptsArray);

    $('#combobox').autocomplete({
        source: deptsArray
    }).on("click", function() {
        console.log("combobox clicked") // works
    });
}

loadCombobox();

数据请求.js

import axios from "axios";

const baseUrl = siteAbsoluteUrl;
const deptList = "Department List";

async function makeGetRequest(url) {
  const response = await axios.get(url, getRequestConfig);
  const { results, __next } = response.data.d;
  return { results, __next };
}

// gives back an array containing all departments, without duplicates
export async function makeDepartmentsRequest() {
  const { results } = await makeGetRequest(
    `${baseUrl}/getbytitle('${deptBPList}')/fields?$filter=EntityPropertyName eq 'Department'`
  );
  return results[0].Choices.results;
}

html:

<input type="text" id="combobox" placeholder="Browse departments">

控制台:

【问题讨论】:

  • index.js 中导入makeDepartmentsRequest,例如import { makeDepartmentsRequest } from 'path-to/data-request'
  • 谢谢@Mohrn。所以如果我想将自动完成的source 设置为部门,我会做类似source: makeDepartmentsRequest.results[0].Choices.results 的事情吗?
  • 不完全。 a) makeDepartmentsRequest 是一个函数,所以我们必须调用它。 b) makeDepartmentsRequest 是一个异步函数,所以我们必须等待它(使用awaitthen

标签: javascript jquery rest autocomplete jquery-ui-autocomplete


【解决方案1】:

这样的结果将是最终结果(请注意,我不知道 makeDepartmentsRequest 返回什么或 #combobox 是什么,所以我无法测试此代码)

import { makeDepartmentsRequest } from "path-to/data-request";

function loadCombobox() {
  makeDepartmentsRequest.then(choices => {
    const source = $.map(depts, function(value, key) {
      return {
        value: value,
        data: key
      };
    });
    $("#combobox")
      .autocomplete({
        source
      })
      .on("click", function() {
        console.log("combobox clicked"); // works
      });
  });
}

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2018-10-05
    • 2021-06-19
    • 1970-01-01
    • 2021-01-28
    • 2022-12-19
    相关资源
    最近更新 更多