Rails Controller的Javascript响应导致Uncaught SyntaxError:意外令牌:

时间:2018-11-25 16:28:11

标签: javascript ruby-on-rails cytoscape.js

我有一个创建关系的表单,并且在提交表单时,将添加新连接节点的javascript代码以及应将它们连接到cytoscape图的关系返回:

表格:

<%= 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');

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

该响应不是有效的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');