我使用 select2 加载远程数据我发送 ajax 请求并正确获取响应,但 processResult 不运行并且不会显示任何内容
JavaScript代码:
var formatProduct=
function(product) {
console.log("formatProduct");
if (product.loading) return product.text;
var markup = '<div class="product-to-compare" data=' + product.id + '>' + product.name + '</div>' ;
return markup;
}
var formatProductSelection =
function (product) {
console.log("formatProductSelection");
return product.name || product.text;
}
$(".js-data-example-ajax").select2({
placeholder: "Search for product",
minimumInputLength: 2,
ajax: {
url: '/product/ajax_product_list/',
dataType: 'json',
quietMillis: 300,
data: function (params) {
var id = $('#product-no-1').attr('data') ;
return {
key: params,
id: id
};
},
processResults: function (data) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatProduct, // omitted for brevity, see the source of this page
templateSelection: formatProductSelection // omitted for brevity, see the source of this page
});
以及我的控制器作为响应返回的 JSON:
{
"items": [
{"id": "55dd980c8242b630cfaf4788", "name": "sallll"},
{"id": "55d58d7a8242b62c6b88504e", "name" : "inja"},
{"id": "55d58d558242b62c6b88504d", "name": "salam"}
]
}
您应该重命名 JSON 以返回
text
而不是 name
。
请注意,如果您使用旧版本的
select2
(<4) you should use results
而不是 processResults
。
processResults: function (data) {
//There is my solution.Just directly manipulate the data
$.each(data.items, function(i, d) {
data.items[i]['text'] = d.name;
});
return {
results: data.items
};
}
就我而言,我正在刷新页面并查找发送来获取搜索数据的 http 请求。因此,请务必进行搜索,以便
processResult
接到电话。
在 JSON 数据中,将 name 重命名为 text。因为 select2 数据只接受列名 id 和 text。
在我的例子中,我将内容类型标头设置为“application/json”并返回“类似 json 响应的内容” 当我强制我的响应为“json_encode”(PHP)时,processResults 被触发
即返回
{results:[{id: 1,text:"one option"},{id: 2, text: "another option"}]}
没用。但是
{"results":[{"id":"1","text":"one option"},{"id":"2","text":"another option"}] }
做到了。 所以从 PHP 返回开始
json_encode( (object)array('results'=>array((object)array('id'=>1, 'text'=>'opt.1'))))
工作正常