Select2"TypeError:a is undefined"错误

Rey*_*rPM 5 javascript jquery json jquery-select2

我有这个代码用于Select2从输入字段创建一个元素:

var codigo_arancelario = $codigo_arancelario.val();

$codigo_arancelario.select2({
    placeholder: "Seleccione un estado",
    ajax: {
        dataType: 'json',
        url: function () {
            return Routing.generate('obtenerCodigoArancelario');
        },
        data: function (codigo_arancelario) {
            return {
                filtro: codigo_arancelario
            }
        },
        results: function (data) {
            var myResults = [];
            $.each(data.entities, function (index, item) {
                myResults.push({
                    'id': item.id,
                    'nombre': item.nombre
                });
            });
            return {
                results: myResults
            };
        }
    },
    formatNoResults: function () {
        return "No se encontró el código";
    },
    formatAjaxError: function () {
        return "No hay conexión con el servidor";
    }
});
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用它时,我在Firebug控制台上收到此错误:

TypeError:a未定义

我检查了响应标头,我得到了一个Content-Type application/json,我也检查了请求标头,因为我在服务器端使用Symfony2并发送X-Requested-With XMLHttpRequest.Symfony2函数返回一个像这样的JSON:

{
   "valid":false,
   "entities":[
      {
         "id":101,
         "codigo":"4545",
         "descripcion":null
      },
      {
         "id":102,
         "codigo":"45455",
         "descripcion":"gfhgfhfghfgh"
      },
      {
         "id":103,
         "codigo":"45457",
         "descripcion":"etert"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

我的代码上的错误在哪里?

Moh*_*mar 6

Select2期望 [{text="john doe",id="1"},{text="jane doe",id="2"}]

所以你需要改变'nombre': item.nombre'text': item.nombre 它应该看起来像如下:

 myResults.push({
       'id': item.id,
       'text': item.nombre
 });
Run Code Online (Sandbox Code Playgroud)