简体   繁体   中英

Select2 “TypeError: a is undefined” error

I've this code for create a Select2 element from an input field:

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";
    }
});

But any time I try to use it I get this error on Firebug console:

TypeError: a is undefined

I checked the Response headers and I got a Content-Type application/json and also I check the Request headers since I'm using Symfony2 in the server side and it send the X-Requested-With XMLHttpRequest . The Symfony2 function return a JSON like this one:

{
   "valid":false,
   "entities":[
      {
         "id":101,
         "codigo":"4545",
         "descripcion":null
      },
      {
         "id":102,
         "codigo":"45455",
         "descripcion":"gfhgfhfghfgh"
      },
      {
         "id":103,
         "codigo":"45457",
         "descripcion":"etert"
      }
   ]
}

Where is the error on my code?

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

so you need to change 'nombre': item.nombre to 'text': item.nombre it should look like followed:

 myResults.push({
       'id': item.id,
       'text': item.nombre
 });

May be your data is wrong formate :
data Type: PlainObject or String or Array Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

see jquery for ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM