I'm using select2
4.0.2 to provide a select box that does an AJAX lookup. But what I'd like to do is display the options in the <option>
tags like a normal <select>
until you start typing, and then go off to the server via AJAX to do more searching when your query string is non-empty.
Basically, the problem is that the AJAX query is a bit slow, but I can pre-load the first result on page load. I don't have to load it as <option>
s, I could stuff them into a JSON array or something.
答案 0 :(得分:0)
这就是我最终要做的事情。在select2 ajax选项中,首先,在数据函数中,我从选项中存储值和文本(因为我在传输函数中无法访问它)。对不起,这是在CoffeeScript中:
data: (params) ->
ret.q = params.term
ret.page = params.page
o = ({
id: $(e).val(),
display_name: $(e).text()
} for e, index in this.children() when index > 0)
ret.options = o
return JSON.stringify(ret)
然后我宣布一个传输函数,决定是否进行ajax调用或使用本地数据:
transport: (params, success, failure) ->
# Get query string
params_data = $.parseJSON(params.data)
q = params_data.q
if !q || q.length < 3
q_reg = new RegExp(q, "i")
data =
incomplete_results: false
items: params_data.options.filter (element) ->
q_reg.test(element.display_name)
success(data)
else
$.ajax(params).done(success).fail(failure)