【发布时间】:2011-05-02 05:06:28
【问题描述】:
大家好,我正在开发一个应用程序,但在使用新的 Rails 3 link_to 时遇到了困难。情况是这样的——我的“主页”页面上有两个 div,每个 div 都使用 ajax 在 document.load 中填充。这按预期工作。
在我加载到这些 div 中的页面内容中,我想使用 link_to... :remote => true 功能。源使用 data-remote="true" 标记按预期呈现,但是当我单击链接时,它们被完全忽略(链接被视为常规超链接)。
我编写的 .rjs 文件可以正确处理所有内容(因为它们在硬编码时可以工作),所以这不是问题。
这里是 ajax 加载内容的 html 源代码:
<div>
<a href="/cart/add/2" data-remote="true">Link A</a>
<a href="/cart/add/1" data-remote="true">Link B</a>
</div>
在通常嵌入页面时单击其中一个链接会导致我的购物车正确更新...但是,当我使用 AJAX 将此内容动态加载到页面中时,链接会跟随并忽略 data-remote= “真”……
最初我认为这与原型在 AJAX 内容中未正确加载有关,但我已经检查了所有这些,它并没有改变任何事情......
我真的很困惑...有人对此有想法吗?
# add method of controller
def add
product = Product.find_by_id(params[:product_id])
params[:quantity] ||= 1
params[:price] ||= product.price
unless product.nil?
@line = session[:cart].purchase_lines.select {|l| l.product_id == product.id}.first
unless @line.nil?
@line.quantity = (@line.quantity + params[:quantity].to_i)
else # create a new purchase_line in the cart
@line = session[:cart].purchase_lines.build({ :product_id => product.id, :price => params[:price], :quantity => params[:quantity].to_i })
end
else
flash[:error] = "Unable to add the selected product"
end
end
还有我的 rjs
# add.rjs
page.if page['product_' << @line.product_id.to_s] do
page.replace 'product_' << @line.product_id.to_s, :partial => 'line'
page.else
page.insert_html :bottom, 'cart', :partial => 'line'
end
page.replace_html 'sub_total', number_to_currency(session[:cart].sub_total, :unit => '$')
page.replace_html 'tax', number_to_currency(session[:cart].tax, :unit => '$')
page.replace_html 'total', number_to_currency(session[:cart].sub_total+session[:cart].tax, :unit => '$')
page.visual_effect :highlight, 'product_' << @line.product_id.to_s, :duration => 1
【问题讨论】:
标签: javascript ruby-on-rails ruby ajax