我有一个带有按钮的页面(筛选器页面),该按钮具有onClick()调用,searchProductsWithParams()脚本函数,按钮是
<button type="button" class="btn btn-primary btn-lg mt-4 py-3 px-5" onclick="searchProductsWithParams()">SEARCH</button>
现在同一页面(“过滤器页面”)上的脚本功能为
function searchProductsWithParams(){
shapesId = [1,2,3]
colorsId = [1,2,3]
$.ajax({
url: '/products/product_list_with_filter_params',
type: 'POST',
data: {
shape_ids: shapesId,
color_ids: colorsId,
}
});
}
此js函数由onClick()调用,这是页面上的按钮事件。
现在,我有一个控制器products_controller.rb,其中有两个操作, 1.index和2.product_list_with_filter_params
def index
@products = Product.all
@view_for = "Products"
end
def product_list_with_filter_params
@products = Product.filter_by_ids(product_filter_ids_params(params))
@view_for = "Products"
respond_to do |format|
format.html { render :index }
end
end
我正在做的事情是在第二种方法中基于主体参数进行一些操作,现在我想要的是使用@products获取index.html页面,但是我的页面没有重定向并坚持使用先前的方法仅页面。 日志记录在下面,
Started POST "/products/product_list_with_filter_params" for ::1 at 2020-05-11 20:40:51 +0530
Processing by ProductsController#product_list_with_filter_params as */*
Parameters: {"shape_ids"=>["all"], "color_ids"=>["all"]}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:9
Rendering products/index.html.erb within layouts/application
Product Load (3.9ms) SELECT "products".* FROM "products" WHERE "products"."is_active" = $1 AND "products"."shape" = $2 AND "products"."color" = $3
[["is_active", true], ["shape", 0]]
↳ app/views/products/index.html.erb:123
Rendered products/index.html.erb within layouts/application (8.0ms)
Cart Load (0.4ms) SELECT "carts".* FROM "carts" WHERE "carts"."user_id" = $1 LIMIT $2 [["user_id", 1], ["LIMIT", 1]]
↳ app/views/layouts/_new_header.html.erb:57
Rendered layouts/_new_header.html.erb (3.2ms)
Rendered layouts/_footer.html.erb (0.2ms)
Completed 200 OK in 129ms (Views: 105.7ms | ActiveRecord: 8.1ms)
现在,我想要的是执行product_list_with_filter_params()方法并执行index.html页面。我知道这不是一个棘手的问题,但是我总是对AJAX感到困惑。
Plz,如果需要更多详细信息,请发表评论?
答案 0 :(得分:0)
正如max指出的那样,AJAX不会重定向浏览器,而是会返回一个响应,您可以从那里决定要做什么。如果您想执行请求而不更改当前页面,则AJAX很有用。
还要指出,您可能要考虑仅使用index
端点来获取全部信息并通过Product
进行过滤,而不是使用具有相同功能的两个端点。