来自Rails控制器的Javascript响应导致未捕获的语法错误:意外的令牌:



我有一个创建关系的表单,当表单提交时,应该返回添加新连接的节点以及将它们连接到细胞景观图的关系的javascript代码:

形式:

<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => @article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, [], {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>

控制器代码:

def add_dependency
@relation = Relation.find_or_create_by(relation_params)
@relation.user << current_user
respond_to do |format|
if @relation.save
elements = json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: @relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: @relation.errors, status: :unprocessable_entity }
end
end
end

我在javascript控制台中收到这个错误(没有"Hello"(:

Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)

这是回应:

ancestors.add( {:edges=>[], :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');

我通过添加to_json:解决了这个问题

json_for_cytoscape(@relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json

该响应不是有效的javascript,原因很简单。当您将Ruby哈希转换为字符串时,结果是无效的JS:

irb(main):001:0> { :foo => 'bar'}.to_s
=> "{:foo=>"bar"}"

相反,您需要将其编码为JSON。

irb(main):003:0> { :foo => 'bar'}.to_json
=> "{"foo":"bar"}"

由于引用问题,如果你真的创建了一个视图而不是内联呈现,那么更容易做到:

ancestors.add( <%= elements.to_json %> ); 
console.log('Hello');

最新更新