HI,當錯誤railscast 197:試圖添加字段使用JavaScript
我試圖按照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;"
所有對我來說似乎都是正確的,我看不出哪裏會出現問題。如果有人有想法。
感謝,
阿蘭
你使用Rails 3?它默認轉義html。 – apneadiving 2011-01-10 23:04:08