HI,
我尝试按照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;"
对我来说一切似乎都是正确的,我不知道问题出在哪里。如果有人有想法。
谢谢,
阿兰
答案 0 :(得分:2)
答案 1 :(得分:2)
您需要删除转义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)}\")")