【问题标题】:When I get data(array) from ajax response, how could I pass it to a partial which will generate a table?当我从 ajax 响应中获取数据(数组)时,如何将其传递给将生成表的部分?
【发布时间】:2017-09-13 14:10:03
【问题描述】:

我的 rails 应用中有一个 Product 模型。
我想在products/index.html.erbAJAX 中实现一个实时搜索表单。
我通过 AJAX 成功获得了搜索结果:

<script>
    var $search_field = $("#key_word");
    var $table_body = $("#products_body");
    $search_field.keyup(function(){
      var search_keyword = $search_field.val();
      var search_options = {
      utf8: "✓",
      key_word: search_keyword
      }
    function display_results(data) {
      console.log(data);                     // Testing if I can get response correctly
    };
    $.getJSON("/products", search_options, display_results)
  }) ;
</script>

检查开发工具的控制台,本地服务器在输入不同的单词时确实会发回正确的搜索结果。Here's a screenshot of dev tool console
以前我实现了一个简单的搜索表单并创建部分 views/products/_list_table 来处理表格。在 products_controller 我定义了@products,所以它可以部分使用。

这是 products_controller 中的index

 def index
   if params[:key_word].present?
     @products = Product.find_by_sql("# some sql code here")
   else
     @products = Product.all
   end
   set_price(@products)
   respond_to do |format|
     format.html # index.html.erb
     format.json { render json: @products}
   end
 end

这是部分内容:

<thead>
  <tr>
      <th>Name</th>
      .
      .
      .    
      <th>Manu</th>
  </tr>
</thead>

<tbody id="products_body">
  <% @products.each do |product| %>
    <tr>
      <td><%= product.name%></td>
      <td><%= product.brand%></td>
      .
      .
      .

    </tr>
  <% end %>
</tbody>

但我不知道如何将 ajax 搜索结果(在这种情况下是 data 后跟 display_result() 函数)传递给部分。
我尝试使用$.each() 循环在脚本中生成新表单,但它使代码变得乏味。应该有一些方法可以将ajax数据发送到partial并以更干燥的方式生成表。

问题:在这种情况下,如何将我从ajax请求中获得的数据发送到部分_list_table,然后使用它来生成产品表?

有人可以帮我吗?谢谢。

【问题讨论】:

    标签: jquery ruby-on-rails ajax


    【解决方案1】:

    http://guides.rubyonrails.org/working_with_javascript_in_rails.html#an-introduction-to-ajax

    例如,下面是一些使用 jQuery 库发出 Ajax 请求的 CoffeeScript 代码:

     $.ajax(url: "/test").done (html) ->
          $("#results").append html
    

    我不知道该怎么做,但我需要了解这一点,所以我正在阅读更多关于 jquery .ajax() 函数的内容

    http://api.jquery.com/jQuery.ajax/

    我的想法是,如果您的 .getJSON() 成功,您应该将结果附加到您的 html 页面。

    $.getJSON("/products", search_options, display_results)
    

    我认为您可以从AJAX response 获取数据,您需要更改您的display_results() 函数

    一旦找到解决方案,请评论我的帖子,以便我阅读。我将阅读文档,如果我理解问题,我会更新我的答案

    发布请求

    基于following video,我认为你应该如下创建一个post请求

    1. 您的提交链接将具有id='submitLink',而表单中的字段将具有id='name'id='brand'

      var $name = $('#name')
      var $brand = $('#brand')
      // When the link is clicked you trigger the function
      $('#submitLink').on('click', function() {
         // Which creates a variable 
         var product = {
            name: $name,
            brand: $brand
         };
         $.ajax({
            type: 'POST',
            url: '/products',
            data: product,
            success: function () {
                // js code to run on success
            },
            error: function () {
                // js code to run on failure
            }
         });
      });
      
    2. 您应该能够转到浏览器的网络选项卡,找到该帖子请求并在您的帖子请求正文中找到您提交给后端的表单数据

    How are parameters sent in an HTTP POST request?

    【讨论】:

    • 感谢您关注我的问题@Fabrizio Bertoglio。我确实想将结果追加到 html 页面中,但是返回的数据是一个包含许多 js 对象的数组,不能直接追加到表中。我需要将其转换为 @products 之类的东西,然后用循环处理它。
    • @Caven 好的,这很简单,您只需要像本指南中那样对该数组使用 javascript 循环,并将每个元素附加到其中一个字段 w3schools.com/js/js_loop_for.asp
    • 我试过这个。但是如何将ruby代码&lt;%= link_to "+", add_to_cart_product_path(product), method: :post %&gt;嵌入到javascript中。[这里是js代码。]你也可以在views/products/_list_table.html.erb中查看部分
    • @Caven 按照指南guides.rubyonrails.org/working_with_javascript_in_rails.html 中的说明进行评估,因为您使用AJAX 的方法非常复杂,无论如何发布请求都需要使用jQuery.post() 完成,这将创建一个@ 987654345@ 向/products 请求,并将在您的请求正文中包含来自productparams。也许看这个视频很容易youtube.com/watch?v=5nL7X1UMWsc
    • 我找到了一个临时解决方案:datatablesRailsCasts#340有简单介绍。
    猜你喜欢
    • 1970-01-01
    • 2018-02-05
    • 2016-07-21
    • 2013-02-22
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多