为什么没有在我的js.erb文件中工作的链接

Why isnt the the link to working in my js.erb file

本文关键字:文件 工作 链接 erb js 我的 为什么      更新时间:2023-09-26

我的js.erb文件中有这个

var cart_item = "<table id='something' style='width:100%'>"; 
cart_item += "<tr><td>";
cart_item += "<%= @contact.name %>";
cart_item += "<%= link_to_remote 'Delete', :url => {:controller => 'registrations', :action => 'destroy' %>";
cart_item += "</td>";
cart_item += "</tr></table>";
$("#cart").append(cart_item);

它只是挂起了,但当我评论掉link_to_funtion时,一切都很好。我甚至试着把它做成一个link_to,但它仍然挂着,什么也没做。。。。我是不是遗漏了什么

将所有这些提取到一个分部,称之为_cart_item.html.erb:

<table id='something' style='width:100%'>
<tr><td>
<%= @contact.name %>
<%= link_to 'Delete', {:controller => 'registrations', :action => 'destroy', :id => @contact.id}, :remote => true %>
</td>
</tr></table>

然后,您的js.erb文件将如下所示:

$("#cart").append(<%= escape_javascript(render(:partial => "cart_item")) %>);

但瑞安·比格仍然是对的,你应该:

  • 使用RESTful路由和路由助手
  • 对AJAX请求使用:remote => true,正如我所做的那样
  • 确保将id传递给destroy操作,以便它知道要销毁哪个对象

四件事。

一:不需要:url选项。您只需将散列作为第二个参数传递给link_to_remote,它就可以工作了。

第二:您应该为此使用URL帮助程序。此外,如果您使用destroy操作,您可能希望传递一个id。这意味着您将执行以下操作:

link_to_remote 'Delete', registration_path(id)

你会为此做类似resources :registrations的事情。虽然,不确定您的申请中是什么注册,所以我真的可以就此提供建议。

第三:最重要的是,您在link_to_remote行中缺少散列的末尾大括号。如果您忽略了它,这将引发语法错误。

第四:link_to_remote在Rails 3.0中已弃用。您应该使用link_to 'Delete', registration_path(id), :remote => true