【问题标题】:Select2: tagging using an array from remote data?Select2:使用来自远程数据的数组进行标记?
【发布时间】:2026-02-07 10:30:01
【问题描述】:

我从 Select2 开始。我想结合“标记支持”和“加载远程数据”(参见http://ivaynberg.github.io/select2/)。

在 HTML 文件的正文中,我现在有一个输入表单:

<input id="topics">

带有“标记支持”,使用由数组给出的标记列表,如 HTML 文件头部的以下脚本所示:

$("#topics").select2({
     placeholder: "Choose topic(s)",    
     tags:["russia", "europe", "obama"]
}); 

我还有一个服务器,使用 Express 在 Node.js 中制作,连接到数据库。我知道如何在服务器端处理与数据库相关的请求(POST 或 GET)。

对于我的 HTML 文件的输入形式,我希望使用服务器提供的数据数组,而不是数组 ["russia", "europe", "obama"]。

我怎么写?

谢谢!

【问题讨论】:

  • 到目前为止你尝试过什么?有ivaynberg.github.io/select2/#data
  • 其实我不知道如何开始,因为我在获取远程数据时看到的示例似乎得到了一个“data.json”文件,这不是我的情况,因为我的服务器必须从 GET 请求发送的是一个数组。

标签: javascript html node.js express jquery-select2


【解决方案1】:

后端

你必须像这样创建一条短途:

app.get('/foo/bar.json', function(req, res){
     //...
     res.send(data);
}

前端

$("#topics").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        url: "/foo/bar.json",
        dataType: 'json',
        results: function (data, page) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return {results: data};
        }
    },
});

JSON 对象可以是/包含数组。见https://ivaynberg.github.io/select2/#data

【讨论】:

  • 谢谢!后端似乎以这种方式工作(我想我对服务器端有点愚蠢)。但是前端在“主题”输入中显示“正在搜索”...
  • 更准确的说,服务器发送的JSON只是一个字符串数组,比如:[ "obama", "ukraine", "russia" ]。如何对前端进行编码以使该数组成为该字段可用的标签列表?
  • @GBC 是的,但也要考虑记录输入和输出值
  • 我查看了有关 Stack Over Flow 的其他问题。 Select2 似乎需要数组中的idtext 才能在表单中使用它。我试过(按照http://*.com/questions/21160225/select2-text-is-undefined-when-getting-json-using-ajax):results: function (data, page) { var newData = []; _.each(data, function (item) { newData.push({ id: item.Id, text: item.DisplayString }); }); return { results: newData }; } ,但它不起作用。
  • 可能是因为 _.each 是异步的。不妨试试 for 循环。