railscast 197:尝试使用javascript添加字段时出错
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了railscast 197:尝试使用javascript添加字段时出错,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2733字,纯文字阅读大概需要4分钟。
内容图文
![railscast 197:尝试使用javascript添加字段时出错](/upload/InfoBanner/zyjiaocheng/672/cfd0974d6e3442738b771bebac90b889.jpg)
嗨,
我尝试遵循197:嵌套模型表单第2部分railscast 197,但是当我尝试通过javascript添加字段时出现此错误:
Uncaught SyntaxError: Unexpected token &
这里的助手:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
和javascript函数:
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
我认为该电话:
- form_for @report do |f|
%h1= f.label :name
%p= f.text_field :name
- f.fields_for :requests do |builder|
= render 'request_fields', :f => builder
%p= link_to_add_fields "Add Request", f, :requests
这是我得到的html:
onclick="add_fields(this, "requests", "<div class=\'fields\'>\n <h1><label for=\"report_requests_attributes_new_requests_query\">Query<\/label><\/h1>\n <input id=\"report_requests_attributes_new_requests_query\" name=\"report[requests_attributes][new_requests][query]\" size=\"30\" type=\"text\" />\n <input id=\"report_requests_attributes_new_requests__destroy\" name=\"report[requests_attributes][new_requests][_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_fields(this); return false;\">remove<\/a>\n <br>\n<\/div>\n"); return false;"
我试图用CGI.unescapeHTML取消转义,我得到了:
"add_fields(this, \"requests\", \"<div class='fields'>\n <h1><label for=\"requests_query\">Query</label></h1>\n <input id=\"requests_query\" name=\"requests[query]\" size=\"30\" type=\"text\" />\n <input id=\"requests__destroy\" name=\"requests[_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_fields(this); return false;\">remove</a>\n <br>\n</div>\n\"); return false;"
一切似乎对我来说都是正确的,我看不出问题出在哪里.如果有人有想法.
谢谢,
阿兰
解决方法:
您需要删除转义HTML的h函数.在application_helper.rb中:
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
应该
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
内容总结
以上是互联网集市为您收集整理的railscast 197:尝试使用javascript添加字段时出错全部内容,希望文章能够帮你解决railscast 197:尝试使用javascript添加字段时出错所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。