未捕获到的SyntaxError:rails link_to代码中的意外令牌<

时间:2019-01-05 19:38:12

标签: ruby-on-rails

enter image description here我正在尝试使用ujs方法来调用控制器中的自定义函数。我收到此错误:

  

未捕获到的SyntaxError:意外令牌<< / p>

我直接尝试使用定制的url。那也不行。

耙道

   room_connected PUT    /rooms/:room_id/connected(.:format) rooms#connected
        rooms GET    /rooms(.:format)                    rooms#index
              POST   /rooms(.:format)                    rooms#create

routes.rb

 resources :rooms do
   put "connected", :to => "rooms#connected", as: :connected
 end

{s {1}}中的js函数

show.html.erb

session.on("connectionCreated", function(event) { connectionCount++; // jqueryFunction("Call from js to jquery"); <%= link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %> displayConnectionCount(); }); 中定义的功能

room_controller.rb

def connected binding.pry @room = Room.find params[:id] # @room.update_attributes(params[:name]) end 6:158未捕获的SyntaxError:Error 1:

行的意外令牌<

<%= link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %>` which gets translated as below: `<a data-remote="true" rel="nofollow" data-method="put" href="/rooms/6/connected">uma7</a>      未调用控制器中定义的“已连接”功能。 请指教。谢谢

尝试过Ajax:

Error 2:

}); 这将引发: session.on("connectionCreated", function(event) { console.log("connectionCreated"); console.log(room.id); connectionCount++; // jqueryFunction("Call from js to jquery"); $.ajax({ type: "PUT", data: JSON.stringify({ room: {name: 'New_room'}, _method:'put' }), url: "/rooms/" + room.id + "/connected", contentType: 'application/json' }).done(function( msg ) { alert( "Data Saved: " + msg ); });

服务器日志:

jquery.self-ee.js?body=1:10255 PUT http://localhost:3000/rooms/6/connected 500 (Internal Server Error)

2 个答案:

答案 0 :(得分:1)

您在JS函数中填充由生成的标签

  <%= link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %>

因此它应该返回有效的JS,而不仅仅是HTML。

我不确定您要在这里实现什么,但是我首先将生成的HTML括在引号中以使其成为正确的JS字符串:

session.on("connectionCreated", function(event) {
  connectionCount++;
  // jqueryFunction("Call from js to jquery");
   '<%= link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %>'
  displayConnectionCount();
});

答案 1 :(得分:1)

问题是您的ruby位于javascript块中,因此它认为它是javascript。像这样转义javascript:

<%= j link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %>

<%= escape_javascript link_to @room.name, room_connected_path(@room), :remote => true, :method => "put" %>

同样-将链接附加到您的DOM,例如:

$('#link').append(<%= j link_to... %>)

js之外: