【问题标题】:Select_tag doesn't get data from json responseSelect_tag 没有从 json 响应中获取数据
【发布时间】:2016-10-18 04:31:46
【问题描述】:

问题

请阅读编辑,它更干净一些。

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 库一起使用来替换选择框。

这是它在浏览器中的外观:

&lt;%= invoice_form.collection_select :client_id, Client.all, :id, :name %&gt; 生成的第一个input 发送正确的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
            }
          ) }

问题

为什么在第一个 input 结果没有插入到 select_tag。为什么第二个输入不发送任何请求?

我正在尝试重新创建这个:Using Select2 with Ruby on Rails

编辑 1

我只是将这两个输入字段更改为一个。

  <h3> Ajax not working </h3>
  <%= invoice_form.collection_select :seller_id, [], :id, :name %> 

它现在正在发送 ajax 请求并获得正确的响应,但不插入数据以选择选项并仍然显示 未找到结果

【问题讨论】:

    标签: jquery ruby-on-rails ajax ruby-on-rails-4 coffeescript


    【解决方案1】:

    Select2 仅适用于 select 输入标签。在第二个选项中,您只是在不是select 标签的输入上应用select2,这就是它不起作用的原因。

    现在为什么 Result 没有显示在 select2 中。

    请注意,select2 期望的响应格式为

    [{id: 1,text: 'Option1'},{id: 2,text: 'Option2'}] 如果响应与上述格式不同,则需要在客户端处理结果。您正在尝试这样做,但您似乎选择了错误的选项。 您需要定义processResult,所以这是执行此操作的脚本。 您可以找到更多详情Select2 Ajax FAQ

    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
              }
           )}
    

    我希望这行得通。

    P.S 请注意,当您使用 select2 的远程选项时,预计您将在服务器端过滤结果,以便 select2 将显示所有返回的结果。

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2017-07-02
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多