[英]Select2: Results not showing using AJAX
我无法使用AJAX将结果显示在Select2中。 这是我的代码:
$(document).ready(function() {
$("#producto").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:3,
ajax: {
url: 'http://foo.foo/listar.json',
dataType: 'jsonp',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table class='product-resultado'><tr>";
if(product.img != undefined) {
html += "<td class='product-image'><img src='"+product.img+"'/></td>";
}
html += "<td class='product-info'>";
html += product.text + "<br />";
html += product.precio_costo + " CRC <br />";
html += "Existencias: " + product.existencias;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
return product.text;
}
使用Javascript控制台,我看到请求返回预期的JSON:
[
{“text”:“Foo Product”,“img”:“#”,“precio_costo”:45,“existencias”:0,“id”:2}
]
我相信结果: function(data, page) { ... }
没有被调用,因为我在那里发出警报而没有发生任何事情。
它只是挂在那里等待结果:
我猜你要回json而不是jsonp,
所以尝试将行dataType: 'jsonp'
更改为dataType: 'json'
,甚至删除整行。
我以前经历过同样的经历。 json结果被这个标准筛选出来,即使实际返回了预期的JSON,很可能是因为json和jsonp被视为两种不同的格式
PS:这更像是评论,但由于我无法对你的问题发表评论,请耐心等待
我认为你不能从ajax调用返回一个值。因为ajax调用是asynchronous
。 而是自己处理结果。 或使用下面链接中给出的callback functions
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.