2014-05-06 37 views
3

我以Select2开头。我想结合“标记支持”和“加载远程数据”(请参阅​​http://ivaynberg.github.io/select2/)。Select2:使用来自远程数据的数组标记?

在一个HTML文件的正文中,我目前有一个输入形式:

<input id="topics"> 

与“标记支持”使用由阵列给定的标签列表,随着头部的下面的脚本HTML文件显示:

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

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

对于我的HTML文件的输入形式,我希望使用由服务器提供的数据数组而不是数组[[俄罗斯],“欧洲”,“奥巴马”]。

我怎么写它?

谢谢!

+1

你到目前为止尝试过什么?有https://ivaynberg.github.io/select2/#data – Vinz243

+0

事实上,我不知道该如何开始,因为我可以看到有关获取远程数据的示例似乎会得到一个“data.json”文件,这不是我的情况,因为我的服务器必须从GET请求发送一个数组。 – GBC

回答

2

后端

你必须创建这样一个短路线:

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

+0

谢谢!后端似乎以这种方式工作(我想我在服务器端有点愚蠢)。但前端显示“搜索”在“主题”输入... – GBC

+0

更准确地说,由服务器发送的JSON只是一个字符串数组,如下所示:'[ “obama”, “ukraine”, “russia” ]'。如何对前端进行编码以使该数组成为可用于该字段的标签列表? – GBC

+0

它猜测我缺少'formatSelection'和'formatInput'的东西... – GBC

相关问题