1

我在 Rails 中使用 jQuery 时遇到了一些麻烦。

我想为特定列表项调用destroy方法,然后通过ajax将其从列表中删除。我的代码很简单:

# _web_profile.html.erb - The partial containing the link to destroy:
<%= link_to 'Remove', web_profile, :method => :delete, :class => 'remove_button' %>

# The ajax hijacking
$('.remove_button').live('click', function() {
  $.ajax({ type: 'delete', url:  this.href });
  return false;
});

# In my controller
format.js { render(:update) { |page| page.remove "web_profile_#{id}" } }

好的,基本上就是这样。当我按下按钮时,一切正常,但是我没有执行脚本,而是在浏览器中得到了一个文本输出:

# Browser output
try {
  jQuery("#web_profile_12").remove();
} catch (e) { 
  alert('RJS error:\n\n' + e.toString()); 
  alert('jQuery(\"#web_profile_12\").remove();'); throw e 
}

知道为什么不执行这个漂亮的 javascript 代码吗?我已经尝试添加dataType到 ajax 请求。

谢谢和最好的问候,乔

4

2 回答 2

0

为什么“类型”设置为“删除”?它应该设置为“POST”,dataType 设置为“script”。由于跨浏览器兼容性问题,应使用变通方法将操作指定为 RESTful 删除。数据应将“_method”参数设置为“delete”。

我建议安装jrails并使用 link_to_remote 和其他 Rails 助手。它们生成正确的 JS 代码。因此,您可以了解如何构建正确的 Rails Ajax 请求。

于 2009-09-16T22:24:51.453 回答
0

您必须在$.ajax()调用中将类型设置为“脚本”,或者将该调用替换为$.getScript()

于 2009-09-17T11:39:49.947 回答