问题
请阅读编辑,它有点干净。
select_tag使用Select2不接收/发送ajax请求。
我试图使用ajax为我的select_tag
获取数据,因为表中有很多行。
<h3> Ajax send requests but I have Client.all </h3>
<%= invoice_form.collection_select :client_id, Client.all, :id, :name %>
<h3> Ajax not working </h3>
<input id="invoice_seller_id" />
这些标记与Select2库一起使用来替换复选框。
这就是它在浏览器中的样子:
首先,从input
生成的<%= invoice_form.collection_select :client_id, Client.all, :id, :name %>
发送正确的json请求,甚至得到正确的响应。
但是有信息没有找到结果。
在第二种方法中,浏览器甚至不发送ajax请求。
代码
发票/_form.html.erb
<h3> Ajax send requests but I have Client.all </h3>
<%= invoice_form.collection_select :client_id, Client.all, :id, :name %>
<h3> Ajax not working </h3>
<input id="invoice_seller_id" />
invoice.js.coffee
jQuery ->
$('#invoice_client_id').select2
theme: 'bootstrap'
ajax:
url: '/clients.json'
dataType: 'json'
results: (data, page) ->
{ results: $.map(data, (client, i) ->
{
id: client.id
text: client.name
}
) }
$('#invoice_seller_id').select2
theme: 'bootstrap'
ajax:
url: '/clients.json'
dataType: 'json'
results: (data, page) ->
{ results: $.map(data, (client, i) ->
{
id: client.id
text: client.name
}
) }
问题
为什么在第一次输入结果没有插入到select_tag。为什么第二输入不发送任何请求?
我试着重新创造这个:在Rails中使用Select2
编辑1
我只换了一个就把这两个田地换了。
<h3> Ajax not working </h3>
<%= invoice_form.collection_select :seller_id, [], :id, :name %>
它现在正在发送ajax请求并得到正确的响应,但是不要插入数据来选择选项,仍然显示没有找到任何结果
发布于 2016-06-16 08:07:24
Select2
只适用于select
输入标记。在第二个选项中,您只是在输入上应用select2
,这不是select
标记,这就是它不能工作的原因。
现在,为什么结果没有显示在select2中。
请注意,select2
希望得到以下形式的答复:
[{id: 1,text: 'Option1'},{id: 2,text: 'Option2'}]
如果响应与上述格式不同,则需要在客户端使用processResults。你正在尝试做这件事,但似乎你选择了错误的选择。您需要定义processResult
,因此下面是执行此操作的脚本。你可以找到更多的细节Select2 Ajax常见问题
jQuery ->
$('#invoice_client_id').select2
theme: 'bootstrap'
ajax:
url: '/clients.json'
dataType: 'json'
processResults: (data) ->
return {
results: $.map(data, (client, i) ->
{
id: client.id
text: client.name
}
)}
我希望这能行。
请注意,当您使用select2的远程选项时,预期您将在服务器端过滤结果,以便select2将显示所有返回的结果。
https://stackoverflow.com/questions/37862882
复制