Javascript 选择2:不使用AJAX显示结果
我很难使用AJAX将结果显示在Select2中。 这是我的密码:Javascript 选择2:不使用AJAX显示结果,javascript,ajax,jsonp,jquery-select2,Javascript,Ajax,Jsonp,Jquery Select2,我很难使用AJAX将结果显示在Select2中。 这是我的密码: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productFormatResult, formatSelection: productFormatSelection, dropdownClass: '
$(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:
[
{文本:Foo Product,img:,precio_costo:
45,存在性:0,id:2}
]
我相信结果是:functiondata,{…}页没有被调用,因为我在那里放了一个警报,什么也没有发生
它只是挂在那里等待结果:
我认为您不能从ajax调用返回值,因为ajax调用是异步的。而是自己处理结果。或者使用下面链接中给出的回调函数
请看我猜您返回的是json而不是jsonp 因此,请尝试将行数据类型:“jsonp”更改为数据类型:“json”, 甚至把整条线都拆了 我以前也有过同样的经历。json结果通过此标准筛选出来, 即使实际返回了预期的JSON,也很可能是因为 json和jsonp被视为两种不同的格式
PS:这更像是一个评论,但因为我不能对你的问题发表评论,请耐心听我说这不是一个简单的Ajax调用,而是一个插件。或者您知道数据和结果回调是如何工作的吗?是的,从文档中可以看出,该对象作为一种快捷方式,必须手动编写执行ajax请求的函数。内置函数支持更高级的功能,例如限制和删除无序响应。-@Felix Kling ya我知道回调是如何工作的,比如传递函数指针,以便指针调用函数。另外,我知道ajax调用是异步的,它不能返回值。我认为OP在这方面是落后的,因为ajax的概念在任何地方都是一样的,因此给出了一个建议。所以,我在回答中加入了“我想”。我承认,我不知道他工作的具体情况。我的回答有错吗??