选择二:"文字是未定义"获取JSON时用ajax [英] select2: "text is undefined" when getting json using ajax
问题描述
我在收到的JSON结果反馈给选择2时的一个问题。我的JSON不返回的结果,有一个文本字段,以便需要格式化的结果,这样选择二接受名称。
I'm having an issue when getting json results back to select2. My json does not return a result that has a "text" field so need to format the result so that select2 accepts "Name".
这code如果在JSON文本字段设置为文本,但在这种情况下,我不能改变的JSON结果(我的控制范围之内code)格式的作品。
This code works if the text field in the json is set to "text" but in this case, I cannot change the formatting of the json result (code outside my control).
$("#e1").select2({
formatNoMatches: function(term) {return term +" does not match any items." },
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "localhost:1111/Items.json",
dataType: 'jsonp',
cache: true,
quietMillis: 200,
data: function (term, page) {
return {
q: term, // search term
p: page,
s: 15
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
var numPages = Math.ceil(data.total / 15);
return {results: data.Data, numPages: numPages};
}
}
});
我已经调查的文档,发现了一些语句就可以投入的结果,如
I have looked into the documentation and found some statements you can put into the results such as
text: 'Name',
但我仍然得到文本未定义。
but I am still getting "text is undefined".
感谢您的帮助。
推荐答案
注意,选择2始终处于{ID,文字}对,所以你需要指定
note that select2 is always in {id,text} pair so you need to specify both
results: function (data, page) {
var newData = [];
_.each(data, function (item) {
newData.push({
id: item.Id //id part present in data
, text: item.DisplayString //string to be displayed
});
});
return { results: newData };
}
},
这篇关于选择二:"文字是未定义"获取JSON时用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!