【发布时间】:2014-07-04 15:04:24
【问题描述】:
我的show.html.erb 页面中有一个数组,并希望使用 Ajax 请求将它从 javascript 传递给控制器中的方法,但它给了我错误 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 的 javascript 中的 AJAX 调用:
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);
}
解决了在下面的 cmets 中,只需要删除由脚手架创建的自动生成的方法,这些脚手架正在为节目创建对象,更新 .. 等
【问题讨论】:
-
你的布局标题中有 吗?
标签: ruby-on-rails ajax csrf