javascript Select2 "TypeError: a is undefined" 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26500449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select2 "TypeError: a is undefined" error
提问by ReynierPM
I've this code for create a Select2
element from an input field:
我有这个用于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";
}
});
But any time I try to use it I get this error on Firebug console:
但是每当我尝试使用它时,我都会在 Firebug 控制台上收到此错误:
TypeError: a is undefined
类型错误:a 未定义
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:
我检查了响应头,我得到了一个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"
}
]
}
Where is the error on my code?
我的代码错误在哪里?
回答by Mohit Kumar
Select2 expects [{text="john doe",id="1"},{text="jane doe",id="2"}]
Select2 期望 [{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:
所以你需要改变'nombre': item.nombre
到'text': item.nombre
它应该看起来像如下:
myResults.push({
'id': item.id,
'text': item.nombre
});
回答by Feng Lin
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).
可能是您的数据格式错误:
数据类型:PlainObject 或 String 或 Array 要发送到服务器的数据。如果不是字符串,则将其转换为查询字符串。它附加到 GET 请求的 url。请参阅 processData 选项以防止此自动处理。对象必须是键/值对。如果 value 是一个数组,jQuery 会根据传统设置的值(如下所述)序列化具有相同键的多个值。
see jquery for ajax