Rails Auth Token和Ajax

好吧,从我在其他网站上看到的和堆栈溢出,Rails抛出此身份validation令牌错误,因为我的表单没有传递令牌 – 这是一个安全function。 我明白了。

但是我真的没有表格。 我在这里有ajax – 我的javascript将id’ed信息发布到处理函数中。

所以我的问题是,如何将身份validation令牌提供给我的控制器?

我的观点如下:

    <tr title = "Purchases " > ?      n/a n/a  -$   

相应的ajax如下:

 /* send ids by ajax */ $('#tableActions li a').click(function() { if(!$(this).hasClass('disabled')) { action = $(this).text(); ids = new Array(); i = 0; $('td.check input','#tableHolder').each(function() { if($(this).attr('checked')) { ids[i++] = $(this).parents('tr').attr('title'); } }); $.ajax({ type: "POST", url: "/bulkaction", data: "=" + action + "&ids=" + ids + "&authenticity_token=" + encodeURIComponent(AUTH_TOKEN), success: function(data){ $('#tableHolder').html(data); /* bring back all functionality */ initTable(); /* set default sorting by date desc */ $('th').removeClass('sortUp sortDown'); $('th:eq(1)').addClass('sortDown'); /* disable all actions */ $('#tableActions li a').addClass('disabled'); } }); } return false; }); 

我在控制器中的处理逻辑看起来像

  def bulkaction if request.post? ids = params[:ids] #Need to create a function here to parse out my string puts ids #for testing purposes, just put my ids onto the console end puts "This function was accessed and ran." end 

最后控制台说

 Processing UserController#bulkaction (for ::ffff:xx.xxx.xxx.xxx at 2009-07-06 23 :29:49) [POST] Parameters: {"ids"=>"Purchases 10040963"} ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticit yToken): /usr/local/lib/ruby/1.8/webrick/httpserver.rb:104:in `service' /usr/local/lib/ruby/1.8/webrick/httpserver.rb:65:in `run' /usr/local/lib/ruby/1.8/webrick/server.rb:173:in `start_thread' /usr/local/lib/ruby/1.8/webrick/server.rb:162:in `start' /usr/local/lib/ruby/1.8/webrick/server.rb:162:in `start_thread' /usr/local/lib/ruby/1.8/webrick/server.rb:95:in `start' /usr/local/lib/ruby/1.8/webrick/server.rb:92:in `each' /usr/local/lib/ruby/1.8/webrick/server.rb:92:in `start' /usr/local/lib/ruby/1.8/webrick/server.rb:23:in `start' /usr/local/lib/ruby/1.8/webrick/server.rb:82:in `start' 

如果有人能告诉我出错的地方会很有帮助。

解决了! 将ajax改为

 data: "=" + action + "&ids=" + ids + "&authenticity_token=" + AUTH_TOKEN, 

我为每一页添加了头部

 <%= javascript_tag "const AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %> 

如果您使用jQuery,这种技术很有效。

http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery

网站henrik.nyh.se似乎失败了。 那里的版本还包含一个错误,它将get请求转换为使用Internet Explorer的发布请求。 此修复版本来自: http : //www.justinball.com/2009/07/08/jquery-ajax-get-in-firefox-post-in-internet-explorer/

 jQuery(document).ajaxSend(function(event, request, settings) { if (typeof(AUTH_TOKEN) == "undefined") return; if (settings.type == 'GET') return; // Don't add anything to a get request let IE turn it into a POST. settings.data = settings.data || ""; settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN); });