我的show.html.erb
页面中有一个数组,想要使用Ajax请求将其从javascript传递到Controller中的方法,但它给了我错误HTTP/1.1 422 Unprocessable Entity
Can't verify CSRF token authenticity
和我不知道在哪里搜索
这是我的日志:
Started PUT "/new_surveys/submit" for 127.0.0.1 at 2014-05-15 19:26:12 +0200
Processing by NewSurveysController#update as JSON
Parameters: {"arrays"=>["valueSelected"], "id"=>"submit", "new_survey"=>{}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 15ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
这是处理此部分的路径文件的一部分
resources :new_surveys
put "/new_surveys/submit", to: 'new_surveys#submit'
我的控制器,在搜索了大部分答案之后只是添加了skip_before_filter
,但它从一开始就出现了同样的错误
class NewSurveysController < ApplicationController
before_action :set_new_survey, only: [:show, :edit, :update, :destroy, :submit]
skip_before_filter :verify_authenticity_token, only: [:submit]
# GET /new_surveys
# GET /new_surveys.json
def index
@new_surveys = NewSurvey.all
end
def submit
data = params[:arrays]
some code ..
end
这是我在show.html.erb
:
function create_ajax_request (url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Accept', 'application/json'); // I want JSON
xhr.responseType = "json";
xhr.addEventListener('load', function() {
xhr.responseJSON = xhr.response;
console.log(xhr.responseJSON);
callback(xhr.responseJSON, xhr);
});
xhr.send( JSON.stringify(data) );
return xhr;
}
function submit()
{
var SelectedValue = [];
var name = 0;
var radios = document.getElementsByTagName("input");
for(var i=0; i<radios.length; i++) {
if(radios[i].checked)
{
var valueSelected = radios[i].value;
window.alert(valueSelected);
SelectedValue.push("valueSelected")
}
}
var url = ['http://' + location.host, 'new_surveys', 'submit'].join('/');
var callback = function(responseJSON, xhr) {
}
create_ajax_request(url, {arrays: SelectedValue}, callback);
}
已解决,只需删除由脚手架创建的自动生成的方法,这些方法正在为show创建对象,更新..等等
答案 0 :(得分:1)
您需要在ajax请求中发送标头。
var metaTags = document.getElementsByTagName('meta');
for ( var i = 0; i < metaTags.length; i++) {
if (metaTags[i].name === 'csrf-token') {
xhr.setRequestHeader('X-CSRF-Token', metaTags[i].content);
}
}
通过jquery-rails gem使用ajax功能将免费提供:)
答案 1 :(得分:1)
已解决
只需删除由脚手架创建的自动生成的方法,这些方法正在为show创建对象,更新..等等