如何添加真实性令牌?

时间:2010-06-29 13:26:19

标签: ruby-on-rails google-closure-library authenticity-token

我最近切换到谷歌关闭一个新项目。我在向ajax调用中的标头添加真实性令牌时遇到问题。我该怎么做呢?

我的Ajax片段(使用goog.net.XhrIo类):

var initialHTMLContent = superField[i].getCleanContents();

var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
  body: initialHTMLContent
 }));

 goog.net.XhrIo.send('/blogs/create', function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });

在后端使用rails。

更新

日志:

Processing BlogsController#create (for 127.0.0.1 at 2010-06-29 20:18:46) [PUT]
  Parameters: {"authenticity_token"=>""}

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):


Rendered rescues/_trace (272.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (unprocessable_entity)

2 个答案:

答案 0 :(得分:15)

在rails视图(.html.erb文件)中的某个位置,您可以像这样设置一个js变量:

window._token = '<%= form_authenticity_token %>';

然后将其附加到您的电话中:

 goog.net.XhrIo.send('/blogs/create?authenticity_token=' + window._token, function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });

答案 1 :(得分:2)

Rails现在会自动为其添加元标记,因此您可以在页面javascript中使用:

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mongo="http://www.springframework.org/schema/data/mongo"
          xsi:schemaLocation=
          "http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017"/>
    <mongo:db-factory dbname="allData" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

</beans>