【发布时间】:2017-11-16 21:03:29
【问题描述】:
所以这是我第一次将 ajax 与 rails 一起使用,我设法从控制器中取回“数据”……我现在如何在页面上打印出来?我在网上查找有关 ajax 的信息,但 9 找不到任何与我相同的代码可供参考?
代码将详细信息的显示顺序 ASC 更改为 DESC。
JS 文件
$(".ord-dir-link").on("click", function(e){
e.preventDefault();
$.ajax({
url: '/index_list',
method: 'get',
data: jQuery.param({
option: this.href.split("=")[2],
direction: $('.list-direction').val()
}),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data){
console.log(data)
}
})
});
控制器
def index_list
if params[:option]
@products = @products.order("#{params[:option]} #{params[:direction]}")
respond_to do |format|
format.json { render json: @products.to_json }
end
end
end
和风景
<div class="right-content">
<table class="index-list">
<tr>
<th>Id</th>
<th><%= link_to "Name", index_list_path(option: "product_name"), class: "ord-dir-link"%></th>
<th><%= link_to "Type", index_list_path(option: "type_of_product"), class: "ord-dir-link" %></th>
<th><%= link_to "Section", index_list_path(option: "section"), class: "ord-dir-link" %></th>
<th><%= link_to "Category", index_list_path(option: "category"), class: "ord-dir-link" %></th>
<th><%= link_to "Price", index_list_path(option: "price"), class: "ord-dir-link" %></th>
<th><%= link_to "Discount", index_list_path(option: "discount"), class: "ord-dir-link" %></th>
<th><%= link_to "Views", index_list_path(option: "click_counter"), class: "ord-dir-link" %></th>
<th><%= link_to "Upvotes", index_list_path(option: "upvotes"), class: "ord-dir-link" %></th>
<th><%= select_tag(:direction, options_for_select([ ['ASC', "ASC"], ['DESC', "DESC"]] ), {:class => 'list-direction'}) %></th>
</tr>
<% n = 1 %>
<% @products.each do |x| %>
<tr>
<td><%=n%>.</td>
<td><%=x.product_name%></td>
<td><%=x.type_of_product%></td>
<td><%=x.section%></td>
<td><%=x.category%></td>
<td>£<%=x.price%></td>
<td><%=x.discount if x.discount != nil%></td>
<td><%=x.click_counter%></td>
<td><%=x.upvotes%></td>
<td><%=link_to "View", product_path(x.id)%></td>
<% n += 1 %>
<%end%>
</tr>
</table>
</div>
我需要附加用 javascript 写出的全部内容吗?这似乎是一种冗长而笨拙的方法。
【问题讨论】:
-
如果您的响应是 html,那么是的。您可以将它设置在页面上应该与
html()或append()一起使用的位置。 -
你解决了吗?
-
@jvillian 不,我试过只是不太明白如何访问我想要的部分,当呈现 html 时,我将整个页面返回给我。然后我的笔记本电脑坏了,今天刚拿回来
标签: jquery ruby-on-rails ajax