Step by Step 如何在 rails 项目中包含 selectize.JS 构建 Ajax 请求和 Json 答案?

MMK*_*K74 4 javascript ruby-on-rails selectize.js webpack ruby-on-rails-5

我听说过 lib 调用选择。这听起来不错,可以帮助我展示一些很棒的下拉效果。然而,文档并不容易,我对如何正确实现选择一无所知。我试过使用它,直到使用或实现 ajax 都可以。有什么帮助吗?

出于某些原因,当我将 selectize 调用到select它可以工作的特定类时。但是,当我需要告诉选择组件以发出 ajax 请求并搜索 JSON 文件以获取答案并构建下拉多选时,我遇到了严重的问题。

文档用 github 示例提出了该模式:

$('#select-repo').selectize({
      valueField: 'url',
      labelField: 'name',
      searchField: 'name',
      create: false,
      render: {
        option: function(item, escape) {
          return '<div>' +
          '<span class="title">' +
          '<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source')
          + '"></i>' + escape(item.name) + '</span>' +
          '<span class="by">' + escape(item.username) + '</span>' +
          '</span>' +
          '<span class="description">' + escape(item.description) + '</span>' +
          '<ul class="meta">' +
          (item.language ? '<li class="language">' + escape(item.language) + 
          '</li>' : '') +
          '<li class="watchers"><span>' + escape(item.watchers) + '</span> 
          watchers</li>' +
          '<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>'
          + '</ul>' +
          '</div>';
          }
        },
        score: function(search) {
          var score = this.getScoreFunction(search);
          return function(item) {
             return score(item) * (1 + Math.min(item.watchers / 100, 1));
          };
        },
        load: function(query, callback) {
          if (!query.length) return callback();
            $.ajax({
               url: 'https://api.github.com/legacy/repos/search/' + 
               encodeURIComponent(query),
               type: 'GET',
               error: function() {
               callback();
            },
            success: function(res) {
              callback(res.repositories.slice(0, 10));
            }
        });
     }
 });


Run Code Online (Sandbox Code Playgroud)

我尝试过但没有任何成功,因为我真的不知道如何构建 JSON 文件,查询也是一个非常困难的点。

实际结果是我需要了解在使用该库之前需要构建的步骤。然后一旦完成,我将使用该库与 ajx 请求

v2l*_*lrf 5

欢迎使用堆栈。您提到的几个步骤没有添加大量描述。但是在这里,无论您使用什么 Lib,您都需要阅读并再次阅读其文档。

Rails 和 JavaScript Libs 通过 webpack 协同工作。无论你需要什么库。你会找到你想要的库Yarn

从 selectize.js 库到视图,你至少需要播放一些 file.js、file.rb、file.json、routes.rb 所以这是一个很大的问题......

让我们从那个设置开始,如果需要更多信息,我会花更多时间

您当前的 rails 应用程序是否添加了 webpack?

作为 RoR,我们必须调用一些 JavaScript 库并编写它们的自定义脚本。

旧方法是使用该文件 app/assets/javascripts

现代方法是使用 webpack。例如在这个文件中做一些事情app/javascript/packs/application.js

我想安装了 webpack 是因为你标记了那个词。请注意,可以通过旧方法处理但保持更新

根据上面的链接纱线

使用该命令行在您的应用程序中安装 selectize.js

$ yarn add selectize

这将在您的文件中添加最后一个版本的 selectize package.json

以正确的方式调用 selectize

 $ mkdir app/javascript/components  ## to create a folder to file your JS components 
 $ touch  app/javascript/components/selectize.js ## to create a file to build JS components
Run Code Online (Sandbox Code Playgroud)

移动到您的node_modules文件夹,该文件夹托管您安装或未安装的所有 javascript 库。这个文件夹是你的应用程序的根目录。

(1) 然后找出文件 node_modules/selectize/dist

然后app/javascript/components/selectize.js用你的文本编辑器打开文件,让我们编写基本代码......

# app/javascript/components/selectize.js
import 'selectize/dist/js/selectize.min.js'; # scroll to node folder (1) get that path
import 'selectize/dist/css/selectize.css'; # scroll to node folder (1) get that path

const selectize = () => {
  $('.select-beast').selectize({
      // create: true, (from example on selectize page)
      sortField: 'text'
  });

};

export { selectize }; # app/javascript/packs/application.js will call that const
Run Code Online (Sandbox Code Playgroud)

然后inside app/javascript/packs/application.js用你的文本编辑器打开文件,让我们编写基本代码......

以正确的方式调用 selectize 组件

# inside app/javascript/packs/application.js
import { selectize } from '../components/selectize'; # import the component
// selectize(); # init the component ?? comment that line for now
Run Code Online (Sandbox Code Playgroud)

选择正确选择类的显示表单('.select-beast')

像红宝石一样的东西......

# app/javascript/components/selectize.js
import 'selectize/dist/js/selectize.min.js'; # scroll to node folder (1) get that path
import 'selectize/dist/css/selectize.css'; # scroll to node folder (1) get that path

const selectize = () => {
  $('.select-beast').selectize({
      // create: true, (from example on selectize page)
      sortField: 'text'
  });

};

export { selectize }; # app/javascript/packs/application.js will call that const
Run Code Online (Sandbox Code Playgroud)

你的输出是...

# inside app/javascript/packs/application.js
import { selectize } from '../components/selectize'; # import the component
// selectize(); # init the component ?? comment that line for now
Run Code Online (Sandbox Code Playgroud)

以正确的方式初始化选择

# inside app/javascript/packs/application.js
import { selectize } from '../components/selectize'; # import the component
selectize(); # init the component 
Run Code Online (Sandbox Code Playgroud)

完毕 ?

刷新您的页面就可以了。

如果问题仍然存在...

带有css样式

(来自 selectize 的 css 不起作用?未加载?未提取?..)移至 config/webpacker.yml

<%= form_for @category do |f| %>
   <%= f.text_field :name %>
   <%= f.select(:single_option_ids,
         SingleOption.all.collect {|a| [a.name, a.id]}, 
         {:include_blank => "category select"}, 
         {:class => "select-beast"})-%>
<%end %>

Run Code Online (Sandbox Code Playgroud)

还要检查并确保加载了来自 webpack 的 CSS ......如何知道这一点?看看你的 webpack-dev-server 控制台

<!-- where you want in your app   -->
<select class="select-beast" name="category[single_option_ids]" id="category_single_option_ids"><option value="">category select</option>
   <option value="1">category A</option>
   <option value="2">category B</option>
   ...
   <option value="37">category X</option>
   <option value="38">category Y</option>
   <option value="39">category Z</option>
</select>

Run Code Online (Sandbox Code Playgroud)

'$ 未定义'或 javascript 控制台中的错误

确保您的 webpack 设置包含此行...

# inside app/javascript/packs/application.js
import { selectize } from '../components/selectize'; # import the component
selectize(); # init the component 
Run Code Online (Sandbox Code Playgroud)
# line 51
development:
  <<: *default
  compile: true
  extract_css: true
Run Code Online (Sandbox Code Playgroud)
Version: webpack 4.32.2
Time: 2351ms
Built at: 06/05/2019 9:21:14 AM
                       Asset        Size             Chunks             Chunk Names
css/application-ff5bcd2e.css    7.73 KiB        application  [emitted]  application 
# this line is a css asset from webpack so css from webpack is loaded 
                ...# other lines
? ?wdm?: Compiled successfully.

Run Code Online (Sandbox Code Playgroud)

结束

根据我的说法,没有更好的方法可以从 webpack 和 rails 开始。那么当然,API、JSON、搜索是使用 js 库(如 selectize、choice 甚至 select2 最后)完成的好事情。让我们知道这是否是回答您的问题“逐步……”的良好开端