我在 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 请求中。
谢谢并致以最诚挚的问候, 乔
最佳答案
为什么“类型”设置为“删除”?应将其设置为“POST”并将数据类型设置为“script”。由于跨浏览器兼容性问题,应使用解决方法将操作指定为 RESTful 删除。数据应将“_method”参数设置为“删除”。
我建议安装jrails并使用 link_to_remote 和其他 Rails 助手。它们生成正确的 JS 代码。因此您可以学习如何构建正确的 Rails Ajax 请求。
关于javascript - Rails 和 jquery : script displayed instead of execution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1435278/