【问题标题】:Using AJAX in rails在 Rails 中使用 AJAX
【发布时间】:2014-01-27 09:39:54
【问题描述】:

我已经在 Ruby on rails 中完成了一个搜索应用程序。但现在我需要使用 AJAX 到它,这样搜索操作就不会重新加载新页面。这是 application.js 文件:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(function(){
  $("#autoc").submit(function(){
    $.get(this.action, $this.serialize(),null,"script")
    return false;
  });
});

这是查看页面:

<h4>Results for your search.</h4>
<br>
<br>

<div id="container">
  <% if !(@results.nil?)%>

    <% for prod in @results %>
      <div class="product">
        <div class="image"><%= image_tag(prod.image, :alt => "logo", :size => "75x75") %>       </div>
    <div class="name"><h3> <%= prod.name %> </h3></div>
    <div class="price"><h5>Old Price:</h5><%= prod.maxprice%></div>
        <div class="price"> <h5>New Price:</h5><%= (prod.maxprice)-(prod.maxprice * prod.discount / 100) %></div>   
      </div>
    <% end %>
  <% else %>
    <div class="notice"><%= flash[:alert] %></div>
  <% end %>
</div>

这是我的控制器代码:

def index
  @init = Sunspot.search(Clothes) do
    paginate :page => params[:page], :per_page => 24
    order_by :maxprice
  end
  @first = @init.results
end

def show
  if params[:name] == ""
    @search = []
  else
    @search = Sunspot.search(Clothes) do
      fulltext params[:name]
      paginate :page => params[:page], :per_page => 24
      order_by :maxprice
    end
    @results = @search.results
  end
  flash[:notice] = "Enter something!"
end

def autocomplete
  list=[] 
   @res = Clothes.search do
    fulltext params[:term]
    paginate :page => 1, :per_page => 100
    order_by :maxprice
  end
  @rest = @res.results
  @rest.each do |brand|
    list << {"label"=>brand.name, "value"=>brand.name, "id"=>brand.id}
  end
  respond_to do |format|
    format.json{render :json=>list.to_json, :layout=>false}
  end
end

【问题讨论】:

    标签: jquery ruby-on-rails ajax search


    【解决方案1】:

    您只需设置remote: true 即可启用ajax。

    更多参考可here

    【讨论】:

    • 可能是最简单的方法,但您应该在实际答案中包含更多细节,而不是链接到外部页面。
    【解决方案2】:

    回应

    您需要将结果附加到您的页面

    Ajax 的工作原理是代表您发送请求,并允许您在页面上使用返回的响应。我会这样做:

    #app/assets/javascripts/application.js
    $("#autoc").on("submit", function() {
        $.ajax({
             url: $(this).action,
             data: $(this).serialize(),
             dataType: "json",
             success: function(data) {
                  $("#container").html(data);
             },
             error: function(data) {
                 alert("Sorry, there was an error!");
             }
        });
    });
    

    当然,如果您的控制器操作代码检出!

    【讨论】:

    • 我照你说的做了。但是url中还有一个查询字符串。
    • 我在表单标签中设置了'remote :true'!
    • URL 中的查询字符串来自GET 方法。如果您只想发送纯数据(无查询字符串),则需要使用POST 方法。您可以在我们的开发网站之一上查看示例:firststopcosmeticshop.co.uk
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多