0

我刚开始使用 [select2][1],我正在开发一个需要从 JSON 数据源填充的标签列表(如 StackOverflow 上)的项目。我正在使用在这个问题上找到的一个例子:[Tagging With Ajax In Select2][2] 但我在让它工作时遇到了一些麻烦。

        // Testing JSON load
        $("#testJsonLoad").select2({
            tags: true,
            tokenSeparators: [",", " "],
            createSearchChoice: function (term, data) {

                if ($(data).filter(function () {
                    return this.text.localeCompare(term) === 0;
                }).length === 0) {
                    return {
                        id: term,
                        text: term
                    };
                }
            },
            multiple: true,
            ajax: {
                url: 'data.json',
                dataType: "json",
                data: function (term, page) {
                    return {
                        q: term
                    };
                },
                results: function (data, page) {
                    return {
                        results: data
                    };
                }
            }
        });

仅出于测试目的,data.json 页面中包含以下数据:

{
"data": [
    { "id" : 1, "text" : "Alabama" },
    { "id" : 2, "text" : "Alaska" },
    { "id" : 3, "text" : "Arizona" },
    { "id" : 4, "text" : "Arkansas" },
    { "id" : 5, "text" : "California" },
    { "id" : 6, "text" : "Colorado" },
    { "id" : 7, "text" : "Connecticut" },
    { "id" : 8, "text" : "Delaware" },
    { "id" : 9, "text" : "District of Columbia" },
    { "id" : 10, "text" : "Florida" },
    { "id" : 11, "text" : "Georgia" },
    { "id" : 12, "text" : "Hawaii" },
    { "id" : 13, "text" : "Idaho" } ]
}

我的问题是我收到了这个错误:this.text is undefined - Line 78

return this.text.localeCompare(term) === 0;  

我认为这可能与我的 JSON 格式化方式有关。我尝试了几种不同的格式,但我的大部分在线研究都没有产生积极的结果。

4

3 回答 3

2

结果需要json 中的idtext节点,您可以告诉您的 JSON 使用这些节点名称输出结果,或者指定在 JS 中使用哪个:

来自网站的示例:

query: function (query) {
  var data = {results: []}, i, j, s;
  for (i = 1; i < 5; i++) {
    s = "";
    for (j = 0; j < i; j++) {s = s + query.term;}
    data.results.push({id: query.term + i, text: s});
  }
  query.callback(data);
}
于 2013-04-29T08:49:50.413 回答
0

将调试器放在 if ($(data).filter(function () 之前并检查您在 $(data) 中得到了什么

于 2013-04-06T15:03:24.013 回答
0

我发现了这个问题。我需要在结果 ajax 函数中调用 data.data(在我的示例中)。

例子:

 results: function (data, page) {
                return {
                    results: data.data
                };
            }
于 2013-04-07T15:55:10.717 回答